我如何提高我在Java流中的技能?

问题描述 投票:0回答:1

我有一个Map<Owner, List<Car>>作为ownerMap。我的Car类具有getColor()getPrice()方法。我的Owner类具有getCity()方法。

我想计算按城市分组的汽车。 (例如:布达佩斯:4(汽车))

到目前为止,这是我的代码:

List<String> cities=ownerMap.entrySet()
                .stream()
                .map(m->m.getKey().getCity())
                .distinct()
                .collect(Collectors.toList());
java dictionary stream
1个回答
0
投票

您应该看一下Collectors.groupingByCollectors.counting

例如,类似:

Map<String, Long> cities=ownerMap.entrySet()
            .stream()
            .map(m->m.getKey().getCity())
            .distinct()
            .collect(Collectors.groupingBy(string -> string, Collectors.counting()));

cities.forEach((name, count) -> {
        System.out.println(name + ":" + count);
    });
© www.soinside.com 2019 - 2024. All rights reserved.