Java 8 返回映射的Java 8分组函数<;字符串,整数>;而不是地图<;长字符串>;
我使用下面提到的代码来查找字符串中每个单词出现的次数Java 8 返回映射的Java 8分组函数<;字符串,整数>;而不是地图<;长字符串>;,java-8,java-stream,Java 8,Java Stream,我使用下面提到的代码来查找字符串中每个单词出现的次数 Map<String, Long> map = Arrays.asList(text.split("\\s+")).stream().collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,Collectors.counting())) Map-Map=Arrays.asList(text.split(\\s+)).stream().collect
Map<String, Long> map = Arrays.asList(text.split("\\s+")).stream().collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,Collectors.counting()))
Map-Map=Arrays.asList(text.split(\\s+)).stream().collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,Collectors.counting())
此代码返回Map
我想将此代码转换为返回Map
。我试着用下面的代码
但是它抛出ClassCastException java.lang.Integer不能转换为java.lang.Long
Map<String, Integer> map1 =
map.entrySet().parallelStream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> Integer.valueOf(entry.getValue())));
Map map1=
collect(Collectors.toMap(entry->entry.getKey(),entry->Integer.valueOf(entry.getValue()));
请帮我解决这个问题,我需要它来返回Map您必须将long转换为整数您需要值为
o.getValue().intValue()
Collectors.counting()
不过是收集器。减少(0L,e->1L,Long::sum)
();使用收集器。减少(0,e->1,Integer::sum)
将设置:
Map<String, Integer> map = Arrays.asList(text.split("\\s+")).stream().collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.reducing(0, e -> 1, Integer::sum)
));
Map Map=Arrays.asList(text.split(\\s+)).stream().collector(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::新建,
减少(0,e->1,整数::和)
));
.您可以在计数后执行
Long
到Integer
的转换,如
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));
这是一个单词加一。您可以对toMap
收集器使用相同的方法:
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
.collect(Collectors.toMap(Function.identity(), word -> 1, Integer::sum));
Map Map=Arrays.stream(text.split(\\s+))
.collect(Collectors.toMap(Function.identity(),word->1,Integer::sum));
您能显示完整的语句吗?(包括将结果分配给的变量)。entry->Integer.valueOf(entry.getValue())
到entry.getValue().intValue()
?@Eran请检查更新。有没有办法在第一步本身做同样的事情,而不是在后面做,这是我正在考虑的
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
Collectors.summingInt(word -> 1)));
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
.collect(Collectors.toMap(Function.identity(), word -> 1, Integer::sum));