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 java.util.stream.Collectors
. 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)
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;
}
}
Grouping Emploeyee objects using Java8
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(","))));
}
}
Output:
DeptId:20 Rajesh,Ramana
DeptId:10 Chandra
DeptId:30 Rahul
Happy Learning 🙂