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;

    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 {

    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.

		/* 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.
		/* 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:


Why is the Test method called flatMap? As there is nothing happening which is related to flatMap it could either be a joke or a misunderstanding. just curious.

Posted by Sam on January 14, 2017 at 09:33 AM CET #

Java making a website different lot of url create generate my past experience is not good about Java website development

Posted by sarapaul on January 18, 2017 at 10:54 AM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments