首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Java8计数int的出现次数

使用Java8计数int的出现次数
EN

Stack Overflow用户
提问于 2014-05-29 11:36:04
回答 3查看 46K关注 0票数 44

有没有更好的方法来用Java8计算int的出现次数?

代码语言:javascript
复制
int[] monthCounter = new int[12];
persons.stream().forEach(person -> monthCounter[person.getBirthday().getMonthValue() - 1]++);
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-05-29 12:19:58

尝试:

代码语言:javascript
复制
 Map<Integer, Long> counters = persons.stream()
     .collect(Collectors.groupingBy(p -> p.getBirthday().getMonthValue(), 
         Collectors.counting()));
票数 106
EN

Stack Overflow用户

发布于 2018-10-28 03:16:06

如果您想要将Integer映射为Integer,可以执行以下操作。

代码语言:javascript
复制
Map<Integer, Integer> counters = persons.stream()
    .collect(Collectors.groupingBy(
        p -> p.getBirthday().getMonthValue(),
        Collectors.reducing(0, e -> 1, Integer::sum)));
票数 1
EN

Stack Overflow用户

发布于 2017-06-21 13:10:13

代码语言:javascript
复制
int size = persons.stream().count()
票数 -4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23925315

复制
相关文章

相似问题

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