如何用Java Lambda表达式统计Ticket列表中目的地的出现次数?
解决方法:用Stream分组统计目的地出现次数
嘿,你这里用filter可就走偏啦!filter是用来筛选掉不符合条件的元素的,但你现在要的是把列表按目的地分组,然后统计每组的数量,完全不需要过滤(除非你想排除空目的地的情况,这个后面再说)。
直接用Collectors.groupingBy搭配计数的下游收集器就搞定了,给你两种常用的写法:
写法1:直接得到Integer类型的计数
这种方法用summingInt,每遇到一个元素就加1,最终结果的value是Integer类型,正好符合你要的Map<String,Integer>:
Map<String, Integer> destinationCountMap = tickets.stream() .collect(Collectors.groupingBy( Ticket::getDestination, // 分组依据:每个Ticket的目的地 Collectors.summingInt(t -> 1) // 统计每组元素个数 ));
写法2:处理Long转Integer的情况
如果用Collectors.counting(),它返回的是Long类型,要是你需要转成Integer,可以用collectingAndThen包装一下:
Map<String, Integer> destinationCountMap = tickets.stream() .collect(Collectors.groupingBy( Ticket::getDestination, Collectors.collectingAndThen(Collectors.counting(), Long::intValue) ));
额外提醒:排除空目的地
如果你的列表里可能存在destination为null的Ticket,想把这些排除在外的话,才需要加上filter:
Map<String, Integer> destinationCountMap = tickets.stream() .filter(ticket -> ticket.getDestination() != null) // 过滤掉目的地为空的元素 .collect(Collectors.groupingBy( Ticket::getDestination, Collectors.summingInt(t -> 1) ));
这样就能完美得到你想要的“目的地-出现次数”的Map啦!
内容的提问来源于stack exchange,提问作者CanciuCostin
相关产品推荐
相关产品推荐

