Map<String, Map<String,Integer>> countSum 根据stream String 分组
时间: 2023-11-11 13:43:02 浏览: 37
并计算每组中每个 String 出现的次数,最终返回一个 Map<String, Map<String, Integer>>,其中外层 Map 的 key 是每个分组的名字,内层 Map 的 key 是每个字符串,value 是对应的出现次数。您可以通过以下代码实现:
Map<String, Map<String, Integer>> countSum = list.stream()
.collect(Collectors.groupingBy(s -> s.split(":")[0], // 根据指定规则进行分组
Collectors.toMap(
Function.identity(), // 使用每个字符串本身作为 key
s -> 1, // 统计初始值为 1
Integer::sum))); // 将同样的字符串次数累加
相关问题
Map<String, Map<String,Integer>> countSum stream 转数组
可以使用以下代码将Map<String, Map<String,Integer>> countSum转换为二维数组:
```
int size = countSum.keySet().size();
String[] keys = countSum.keySet().toArray(new String[size]);
int[][] count = new int[size][size];
for (int i = 0; i < size; i++) {
Map<String, Integer> innerMap = countSum.get(keys[i]);
for (int j = 0; j < size; j++) {
count[i][j] = innerMap.getOrDefault(keys[j], 0);
}
}
```
这段代码首先获取countSum的键集合和大小,然后使用toArray()方法将键集合转换为数组。接着使用两重循环遍历数组,通过getOrDefault()方法获取对应的计数值,将其存入二维数组中。
Map<String, Map<String,Integer>> countSum Steam根据key 分组代码实现
答案如下:
Map<String, Map<String, Integer>> countSumStream = dataList.stream()
.collect(Collectors.groupingBy(Data::getKey, Collectors.toMap(Data::getSubKey, Data::getValue,
Integer::sum)));
其中,Data为一个自定义数据类型,包含key、subKey和value三个属性。对数据流进行分组操作,使用Collectors.groupingBy方法,以Data对象的key值作为分组依据,得到一个Map类型的结果。这个结果中,键为key值,值为Map类型,内部再使用Collectors.toMap方法,以Data对象的subKey值作为键,Data对象的value值作为值,实现对数据求和的功能。最后得到的结果类型仍然是Map<String, Map<String, Integer>>。