使用Lambda Expression计算名称数量

时间:2016-04-02 03:21:47

标签: java lambda reduce

如果我试图计算名单中具有某些名字的人数:
我应该得到类似[Bob:2, Joe:1, Mary:1, Kane: 1]

的输出
List<Person> names = Arrays.toList(Bob, Joe, Bob, Mary, Kane);

Map<String, List<int>> = names.stream().collect(
       Collectors.groupingBy(
            Person::getName,
            Collectors.reducing(
                0,
                //Is there a way here I can get the count of the names from the grouping by above this?
                Integer::sum
            )
       )
)

1 个答案:

答案 0 :(得分:4)

鉴于输入:

List<Person> names = Arrays.asList(Bob, Joe, Bob, Mary, Kane);

您可以使用此lambda表达式:

 Map<String, Integer> counts = names.stream().collect(
    Collectors.toMap(Person::getName, counter -> 1, Integer::sum, LinkedHashMap::new)
);

哪个产生:

{Bob=2, Joe=1, Mary=1, Kane=1}

考虑到费德里科的建议,答案可以更新为:

Map<String, Long> counts = names.stream().collect(
    Collectors.groupingBy(Person::getName, LinkedHashMap::new, Collectors.counting()));