我有一个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());
您应该看一下Collectors.groupingBy
和Collectors.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);
});