Java 8分组函数返回Map <string,integer =“”>而不是Map <string,long>

时间:2019-03-26 09:36:17

标签: java-8 java-stream

我正在使用下面提到的代码来查找字符串中每个单词出现的次数。

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())));

请帮助我解决此问题,我需要它来返回地图

3 个答案:

答案 0 :(得分:3)

像这样计数后,您可以将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));

答案 1 :(得分:0)

您必须将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)));

答案 2 :(得分:0)

Collectors.counting()只不过是Collectors.reducing(0L, e -> 1L, Long::sum)source);使用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)
));

Try it here