我正在使用下面提到的代码来查找字符串中出现的每个单词的次数。
Map<String, Long> map = Arrays.asList(text.split("\\s+")).stream().collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,Collectors.counting()))此代码返回Map<String, Long>,我希望将此代码转换为返回Map<String, Integer>。我试着用下面的代码来做这个,
但它抛出的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())));请帮我解决这个问题,我需要它来返回地图
发布于 2019-03-26 10:30:16
您可以在计数后执行Long到Integer的转换,如下所示
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));但是,您也可以首先使用int值类型进行计数:
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
Collectors.summingInt(word -> 1)));这是对每个单词的一个求和。您可以对toMap收集器使用相同的方法:
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
.collect(Collectors.toMap(Function.identity(), word -> 1, Integer::sum));发布于 2019-03-26 09:46:47
必须将long转换为整数,需要将值转换为o.getValue().intValue()。
Map<String, Integer> stringIntegerMap =
stringLongMap.entrySet().stream().collect(toMap(Map.Entry::getKey, o ->
o.getValue().intValue(), (a, b) -> b));有一种方法可以首先将Map<String,Integer>转换为summingInt(x -> 1))
Map<String, Integer> map = Arrays.asList(text.split("\\s+")).stream()
.collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,summingInt(value -> 1)));发布于 2019-03-26 10:27:31
Collectors.counting()不过是Collectors.reducing(0L, e -> 1L, Long::sum) (来源);使用Collectors.reducing(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)
));https://stackoverflow.com/questions/55353829
复制相似问题