Saturday , April 29 2017
Home / java8 / Java 8 groupingBy Example

Java 8 groupingBy Example

In this tutorials, I am going to show you how to group a list of objects in Java 8.

Java 8 groupingBy :

groupingBy() is a static method available in java.util.stream.Collectors. Which is used to grouping the objects on the basic of any key and then it returns a Collector.

Syntax groupingBy :

public static <T,K> Collector<T,?,Map<K,List<T>>>
groupingBy(Function<? super T,? extends K> classifier)

The above groupingBy() method, grouping the input elements(T) according to the classification function and returning the Map as a Collector.

Java 8 groupingBy Example :

In this example we are going to group the Employee objects according to the department ids.

Employee.java


public class Employee{
    private int id;
    private int department;
    private String name;
    
    public Employee(int id, int department, String name) {
        super();
        this.id = id;
        this.department = department;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public int getDepartment() {
        return department;
    }
    public String getName() {
        return name;
    }
    
}

Java8GroupingBy.java

package com.onlinetutorialspoint.java8;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8_GroupingBy {

    public static void main(String[] args) {

        List<Employee> employees = Arrays.asList(
                new Employee(1, 10, "Chandra"), new Employee(1, 20, "Rajesh"),
                new Employee(1, 30, "Rahul"), new Employee(1, 20, "Ramana"));

        Map<Integer, List<Employee>> byDept = employees.stream().collect(
                Collectors.groupingBy(Employee::getDepartment));

        byDept.forEach((k, v) -> System.out.println("DeptId:"
                + k
                + "  "
                + ((List<Employee>) v).stream().map(m -> m.getName())
                        .collect(Collectors.joining(","))));
    }

}

DeptId:20  Rajesh,Ramana
DeptId:10  Chandra
DeptId:30  Rahul

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

User defined sorting with Java 8 Comparator

In this tutorials, we are going to see how to sort user defined objects using …

One comment

  1. smileforsantosh@gmail.com'
    santosh miriyala

    Hi chandrashekhar, its a nice article, Can you please prepare few posts I wish to perform the same grouping mechanism in java 7 or below versions.

Leave a Reply

Your email address will not be published. Required fields are marked *