'Group By one attribute by another attribute of Object
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.
Solution 1:[1]
Your example is not correct you have a HashMap<String, List<Breweries>> but you expect hashMap.entrySet() to return Set<Map.Entry<String, List<BreweriesPOJO>>. It should be Set<Map.Entry<String, List<Breweries>>. when you do Map.Entry#getKey it will return the key in your case the String return by Breweries::getProvince. If you want the list of the Breweries for the current entry use 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();
}
But if you just want the number of Breweries per province you can do this directly like:
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");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JEY |
