Java 8 分组函数返回 Map<String, Integer> 而不是 Map<String,Long>

Luc*_*cie 3 java-8 java-stream

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

Map<String, Long> map = Arrays.asList(text.split("\\s+")).stream().collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,Collectors.counting()))
Run Code Online (Sandbox Code Playgroud)

此代码返回Map<String, Long>我想将此代码转换为 return Map<String, Integer>。我尝试使用下面的代码来做到这一点,

但它抛出 ClassCastException java.lang.Integer cannot be cast to java.lang.Long

Map<String, Integer> map1 = 
 map.entrySet().parallelStream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> Integer.valueOf(entry.getValue())));
Run Code Online (Sandbox Code Playgroud)

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

Hol*_*ger 6

您可以在计数后执行Longto的转换,Integer例如

Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
        Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));
Run Code Online (Sandbox Code Playgroud)

但您也可以首先使用int值类型进行计数:

Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
        Collectors.summingInt(word -> 1)));
Run Code Online (Sandbox Code Playgroud)

这是为每个单词求和一个。您可以对toMap收集器使用相同的方法:

Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.toMap(Function.identity(), word -> 1, Integer::sum));
Run Code Online (Sandbox Code Playgroud)