In this tutorial, 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 Which is used to grouping the objects on the basis 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.
public class Employee {
    private int id;
    private int department;
    private String name;

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


Grouping Emploeyee objects using Java8
package com.onlinetutorialspoint.java8;

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

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 =

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



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

Happy Learning 🙂