Collectors groupingBy() method in Java
This post will discuss the groupingBy() method provided by the Collectors class in Java.
The groupingBy(classifier) returns a Collector implementing a “group by” operation on input elements, grouping elements according to a classification function, and returning the results in a map. Following are some examples demonstrating the usage of this function:
1. Split a list into two sublists
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; // Java program to split a list using `Collectors.groupingBy()` method class Main { public static void main(String[] args) { List<Integer> inputList = Arrays.asList(1, 2, 3, 4, 5); // get the mid-index for splitting the input list into two int midIndex = (inputList.size() - 1) / 2; Map<Boolean, List<Integer>> map = inputList.stream() .collect(Collectors.groupingBy(s -> inputList.indexOf(s) > midIndex)); System.out.println(map); List<List<Integer>> lists = new ArrayList<>(map.values()); System.out.println("The first sublist is " + lists.get(0)); System.out.println("The second sublist is " + lists.get(1)); } } |
Output:
{false=[1, 2, 3], true=[4, 5]}
The first sublist is [1, 2, 3]
The second sublist is [4, 5]
This is equivalent to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.*; class Main { public static void main(String[] args) { List<Integer> inputList = Arrays.asList(1, 2, 3, 4, 5); // get the mid-index for splitting the input list into two int midIndex = (inputList.size() - 1) / 2; Map<Boolean, List<Integer>> map = new HashMap<>(); for (Integer s : inputList) { map.computeIfAbsent(inputList.indexOf(s) > midIndex, k -> new ArrayList<>()).add(s); } System.out.println(map); List<List<Integer>> lists = new ArrayList<>(map.values()); System.out.println("The first sublist is " + lists.get(0)); System.out.println("The second sublist is " + lists.get(1)); } } |
Output:
{false=[1, 2, 3], true=[4, 5]}
The first sublist is [1, 2, 3]
The second sublist is [4, 5]
2. Group students by grades
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; class Student { private String name; private String grade; private int marks; Student(String name, String grade, Integer marks) { this.name = name; this.grade = grade; this.marks = marks; } public String getName() { return name; } public String getGrade() { return grade; } public int getMarks() { return marks; } @Override public String toString() { return getName(); } } // Java program to group students by grades using `Collectors.groupingBy()` class Main { public static void main(String[] args) { List<Student> students = Arrays.asList(new Student("Tom", "A+", 90), new Student("Lisa", "A+", 98), new Student("John", "A", 85), new Student("Joe", "A", 80), new Student("Jason", "E", 35)); Map<String, List<Student>> studentsByGrade = students.stream() .collect(Collectors.groupingBy(Student::getGrade)); for (Map.Entry<String, List<Student>> entry: studentsByGrade.entrySet()) { System.out.println("Students with " + entry.getKey() + " grade are " + entry.getValue()); } } } |
Output:
Students with A grade are [John, Joe]
Students with E grade are [Jason]
Students with A+ grade are [Tom, Lisa]
The groupingBy(classifier, downstream) collector allows the collection of stream elements into a map by grouping elements according to a classifier method and then performing a reduction operation on the values associated with a given key using the specified downstream Collector. Following are some examples demonstrating the usage of this function:
1. Compute average marks of students with the same grades
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; class Student { private String name; private String grade; private int marks; Student(String name, String grade, Integer marks) { this.name = name; this.grade = grade; this.marks = marks; } public String getName() { return name; } public String getGrade() { return grade; } public int getMarks() { return marks; } @Override public String toString() { return getName(); } } // Java program to compute average marks of students with the same grades // using `Collectors.groupingBy()` class Main { public static void main(String[] args) { List<Student> students = Arrays.asList(new Student("Tom", "A+", 90), new Student("Lisa", "A+", 98), new Student("John", "A", 85), new Student("Joe", "A", 80), new Student("Jason", "E", 35)); Map<String, Double> studentsByGrade = students.stream() .collect(Collectors.groupingBy(Student::getGrade, Collectors.averagingInt(Student::getMarks))); for (Map.Entry<String, Double> entry: studentsByGrade.entrySet()) { System.out.println("Students with " + entry.getKey() + " grade have average marks of " + entry.getValue()); } } } |
Output:
Students with A grade have average marks of 82.5
Students with E grade have average marks of 35.0
Students with A+ grade have average marks of 94.0
2. Count the occurrences of elements in a stream
We can also use the Collectors.groupingBy() method to count the frequency of elements present in a stream.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; // Java program to create a frequency map of elements in a stream // using `Collectors.groupingBy()` class Main { public static void main(String[] args) { Map<String, Long> freq = Stream.of("A", "B", "A", "C", "A", "C") .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(freq); } } |
Output:
{A=3, B=1, C=2}
This is equivalent to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Arrays; import java.util.HashMap; import java.util.Map; class Main { public static void main(String[] args) { Map<String, Long> freq = new HashMap<>(); for (String s : Arrays.asList("A", "B", "A", "C", "A", "C")) { freq.merge(s, 1L, Long::sum); } System.out.println(freq); } } |
Output:
{A=3, B=1, C=2}
That’s all about the Collectors class groupingBy() method in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)