Java Collectors groupingBy() Method

The groupingBy() method in Java, part of the java.util.stream.Collectors class, is used to group elements of a stream by a classifier function. This method is useful when you need to organize elements into groups based on a common attribute.

Table of Contents

  1. Introduction
  2. groupingBy() Method Syntax
  3. Understanding groupingBy()
  4. Examples
    • Basic Usage
    • Using groupingBy() with Downstream Collector
  5. Real-World Use Case
  6. Conclusion

Introduction

The groupingBy() method returns a Collector that groups the input elements according to a classifier function and returns a Map whose keys are the result of applying the classifier function to the input elements, and whose corresponding values are Lists of elements that map to the associated key.

groupingBy() Method Syntax

The syntax for the groupingBy() method is as follows:

public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier)

There are also overloaded versions that allow specifying a downstream collector and a map supplier:

public static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)

public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier, Supplier<M> mapFactory, Collector<? super T, A, D> downstream)

Parameters:

  • classifier: A function that classifies input elements.
  • downstream (optional): A collector to apply to the values associated with a given key.
  • mapFactory (optional): A function that provides a new empty map into which the results will be inserted.

Returns:

  • A Collector that groups the input elements.

Throws:

  • This method does not throw any exceptions.

Understanding groupingBy()

The groupingBy() method allows you to group the elements of a stream by a specified classifier function. This is useful for organizing data into categories based on a common attribute, such as grouping people by age or grouping transactions by type.

Examples

Basic Usage

To demonstrate the basic usage of groupingBy(), we will create a list of strings and group them by their length.

Example

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

public class GroupingByExample {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "fig", "grape");

        // Group the words by their length
        Map<Integer, List<String>> groupedByLength = words.stream()
                                                          .collect(Collectors.groupingBy(String::length));

        System.out.println("Grouped by Length: " + groupedByLength);
    }
}

Output:

Grouped by Length: {3=[fig], 4=[date], 5=[apple, grape], 6=[banana, cherry]}

Using groupingBy() with Downstream Collector

This example shows how to use groupingBy() with a downstream collector to group elements and apply additional operations, such as counting the number of elements in each group.

Example

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

public class GroupingByWithDownstreamExample {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "fig", "grape");

        // Group the words by their length and count the number of words in each group
        Map<Integer, Long> groupedByLengthWithCount = words.stream()
                                                           .collect(Collectors.groupingBy(
                                                               String::length,
                                                               Collectors.counting()
                                                           ));

        System.out.println("Grouped by Length with Count: " + groupedByLengthWithCount);
    }
}

Output:

Grouped by Length with Count: {3=1, 4=1, 5=2, 6=2}

Real-World Use Case

Grouping People by Age

In real-world applications, the groupingBy() method can be used to group people by age.

Example

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

public class GroupingByAgeExample {
    static class Person {
        String name;
        int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        int getAge() {
            return age;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35),
            new Person("David", 30),
            new Person("Eve", 25)
        );

        // Group people by age
        Map<Integer, List<Person>> groupedByAge = people.stream()
                                                        .collect(Collectors.groupingBy(Person::getAge));

        System.out.println("Grouped by Age: " + groupedByAge);
    }
}

Output:

Grouped by Age: {35=[Charlie], 25=[Bob, Eve], 30=[Alice, David]}

Conclusion

The Collectors.groupingBy() method is used to group elements of a stream by a classifier function. This method is particularly useful for organizing elements into categories based on a common attribute. By understanding and using this method, you can efficiently manage grouping operations in your Java applications.

Comments