有人能帮我吗。我有一个对象列表--在我的例子中,有啤酒厂。每个啤酒厂都有一些属性(字段),如名称、入口、id、省(所处的状态)等。一个啤酒厂(名字)可以设在许多省份。现在我需要解决这个问题:每个州的啤酒厂数量如何?所以,把名字按省份分组。所有数据正在从csv文件中读取。我已经创建了回传啤酒清单的阅读器。当我尝试这个:
Map<String, List<Breweries>> hashMap = new HashMap<>();
hashMap = list.stream().collect(Collectors.groupingBy(Breweries::getProvince));
for (Map.Entry<String, List<BreweriesPOJO>> stringListEntry : hashMap.entrySet()) {
System.out.println(stringListEntry.getKey());
}这将返回me键(省)和整个对象作为值。
我已经坐了几个小时了。我没有主意了。
发布于 2022-04-11 15:00:36
您的示例是不正确的,您有一个HashMap<String, List<Breweries>>,但是您希望hashMap.entrySet()返回Set<Map.Entry<String, List<BreweriesPOJO>>。应该是Set<Map.Entry<String, List<Breweries>>。当您执行Map.Entry#getKey时,它将返回密钥--在您的情况下-- String由Breweries::getProvince返回。如果需要当前条目的Breweries列表,请使用Map.Entry#getValue
Map<String, List<Breweries>> hashMap = list.stream().collect(Collectors.groupingBy(Breweries::getProvince));
for (Map.Entry<String, List<Breweries>> stringListEntry : hashMap.entrySet()) {
List<Breweries> breweries = stringListEntry.getValue();
}但是,如果你只想要每个省的啤酒厂数量,你可以直接这样做:
Map<String, Long> hashMap = list.stream().collect(Collectors.groupingBy(Breweries::getProvince, Collectors.counting()));
for (Map.Entry<String, Long> entry : hashMap.entrySet()){
System.out.println(entry.getKey() + ": " + entry.getValue() + " Breweries");
}https://stackoverflow.com/questions/71829871
复制相似问题