gpt4 book ai didi

java-8 - Java 8 分组函数返回 Map 而不是 Map

转载 作者:行者123 更新时间:2023-12-02 11:49:39 42 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

关于java-8 - Java 8 分组函数返回 Map<String, Integer> 而不是 Map<String,Long>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55353829/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com