Java 8 groupingBy Example 📎
A developer has a favorite programming language:
public class Developer {
private int age;
private String favoriteLanguage;
public Developer(int age, String favoriteLanguage) {
this.age = age;
this.favoriteLanguage = favoriteLanguage;
}
public int getAge() {
return age;
}
public String getFavoriteLanguage() {
return favoriteLanguage;
}
@Override
public String toString() {
return "Developer{" + "age=" + age + ", favoriteLanguage=" + favoriteLanguage + '}';
}
}
A team has more than one developers. Now we would like to group the developers by their favorite language.
Collectors#groupingBy
groups classes by properties out-of-the-box:
public class GroupingByTest {
@Test
public void groupByFavoriteLanguage() {
List<Developer> team = Arrays.asList(
new Developer(18, "java"),
new Developer(20, "java"),
new Developer(35, "javascript"),
new Developer(50, "javascript"),
new Developer(50, "logo"));
Map<String, List<Developer>> developersByLanguages = team.
stream().
collect(Collectors.groupingBy(Developer::getFavoriteLanguage));
System.out.println(developersByLanguages);
/* output:
{java=[Developer{age=18, favoriteLanguage=java}, Developer{age=20, favoriteLanguage=java}],
logo=[Developer{age=50, favoriteLanguage=logo}],
javascript=[Developer{age=35, favoriteLanguage=javascript}, Developer{age=50, favoriteLanguage=javascript}]
}
*/
Map<String, Double> favoriteLanguageByAverageAge = team.
stream().
collect(Collectors.groupingBy(Developer::getFavoriteLanguage,
Collectors.averagingInt(Developer::getAge)));
System.out.println(favoriteLanguageByAverageAge);
/* output:
{java=19.0, logo=50.0, javascript=42.5}
*/
}
}
Related: Java 8 CompletableFuture Example
See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.