Collectors
class?Collectors
is a utility class that provides various implementations of reduction operations such as grouping elements, collecting elements to different collections, summarizing elements according to various criteria, etc. The different functionalities in the Collectors
class are usually used as the final operation on streams.
groupingBy()
methodgroupingBy()
is a static method of the Collectors
class used to return a Collector
that helps group the input elements according to a classification function. The elements are mapped to a key as classified by the classification function. All the elements for the same key will be stored in a List
. All the keys with the respective elements in the List
will be stored in a Map
.
The groupingBy()
method is defined in the Collectors
class. The Collectors
class is defined in the java.util.stream
package.
To import the Collectors
class, use the following import statement:
import java.util.stream.Collectors;
public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier)
Function<? super T, ? extends K> classifier
: The classification function.This method returns a Collector
that groups the elements based on the classification function.
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.Map;public class Main {static class Student{int grade;String name;public Student(int grade, String name) {this.grade = grade;this.name = name;}@Overridepublic String toString() {return "Student{" +"grade=" + grade +", name='" + name + '\'' +'}';}}public static void main(String[] args){List<Student> studentList = Arrays.asList(new Student(2, "sam"),new Student(2, "john"),new Student(4, "john"),new Student(4, "Lilly"),new Student(5, "mason"));Map<Integer, List<Student>> groupedStudents = studentList.stream().collect(Collectors.groupingBy(s -> s.grade));System.out.println("Grouped Students according to their grade - " + groupedStudents);}}
In the code above,
Student
class that consists of the grade
and name
as fields. The class has a constructor that initializes the value of the fields and the toString()
method.groupingBy()
method. The classification function here returns the grade
value for every Student
object passed.