Monday , November 20 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 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.

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;

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 🙂

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+ ,


User defined sorting with Java 8 Comparator

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


    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.

  1. Pingback: Milana Travis

Leave a Reply

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