谁能帮我。我有一个对象列表 - 就我而言,有啤酒厂。
每个酿酒厂都有一些属性(字段),例如名称,地址,ID,省(州位置)等...一个Brewerie(名称)可以位于许多省份。现在我需要解决问题:如何在每个状态下服用数量的啤酒厂?因此,按省份分组名称。所有数据都是从CSV文件读取的。我创建了读者,其中返回列表OD Breweries。
当我尝试一下时:
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());
}
这将使我返回密钥(省)和整个对象作为值。
我坐在它上了几个小时。我没有想法。
can anyone help me. I have a list of Objects - in my case there are breweries.
Each brewerie has some attributes(fields) like name, adress, id, province(the state where is situated) etc... One brewerie (name) can be situated in many provinces. Now i need solve the problem: how to take number of breweries in each state? So, grouping Names by Provinces. All data is reading from csv file. I've created the Reader which return List od Breweries.
When i try this:
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());
}
this returns me key(Province) and whole object as a value.
I've been sitting on it for a few hours. I'm out of ideas.
发布评论
评论(1)
您的示例不正确,您有一个
HashMap>
但您希望hashMap.entrySet()
返回Set>
。它应该是Set>
。当您执行Map.Entry#getKey
时,它将返回您的情况下的密钥,即Breweries::getProvince
返回的String
。如果您想要当前条目的Breweries
列表,请使用Map.Entry#getValue
但如果您只想要每个省的啤酒厂数量,您可以直接执行此操作,如下所示:
Your example is not correct you have a
HashMap<String, List<Breweries>>
but you expecthashMap.entrySet()
to returnSet<Map.Entry<String, List<BreweriesPOJO>>
. It should beSet<Map.Entry<String, List<Breweries>>
. when you doMap.Entry#getKey
it will return the key in your case theString
return byBreweries::getProvince
. If you want the list of theBreweries
for the current entry useMap.Entry#getValue
But if you just want the number of Breweries per province you can do this directly like: