首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java 8分组函数返回Map<String、Integer>而不是Map<String、Long>

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

Stack Overflow用户
提问于 2019-03-26 09:36:17
回答 3查看 1K关注 0票数 3

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

代码语言:javascript
复制
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。

代码语言:javascript
复制
Map<String, Integer> map1 = 
 map.entrySet().parallelStream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> Integer.valueOf(entry.getValue())));

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-26 10:30:16

您可以在计数后执行LongInteger的转换,如下所示

代码语言:javascript
复制
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
        Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));

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

代码语言:javascript
复制
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
        Collectors.summingInt(word -> 1)));

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

代码语言:javascript
复制
Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.toMap(Function.identity(), word -> 1, Integer::sum));
票数 8
EN

Stack Overflow用户

发布于 2019-03-26 09:46:47

必须将long转换为整数,需要将值转换为o.getValue().intValue()

代码语言:javascript
复制
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))

代码语言:javascript
复制
 Map<String, Integer> map = Arrays.asList(text.split("\\s+")).stream()
.collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,summingInt(value -> 1)));
票数 0
EN

Stack Overflow用户

发布于 2019-03-26 10:27:31

Collectors.counting()不过是Collectors.reducing(0L, e -> 1L, Long::sum) (来源);使用Collectors.reducing(0, e -> 1, Integer::sum)代替,您将被设置为:

代码语言:javascript
复制
Map<String, Integer> map = Arrays.asList(text.split("\\s+")).stream().collect(Collectors.groupingBy(
    Function.identity(),
    LinkedHashMap::new,
    Collectors.reducing(0, e -> 1, Integer::sum)
));

在这里试试

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55353829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档