Course contentsShow
← Java
Lesson 1568 of 2,87034. Collectors in DepthFree lesson

Basic groupingBy Syntax and Classifier Functions

Understand the classifier function that determines which key each element belongs to in the resulting Map.

Basic groupingBy Syntax and Classifier Functions

You'll learn how to use classifier functions to partition stream elements into groups based on a key you define.

The Core Idea

Collectors.groupingBy() transforms a stream into a Map where elements are grouped by categories. The classifier function is the heart of this operation—it's a function that examines each element and returns a key that determines which group (bucket) that element belongs to.

Think of sorting mail into mailboxes: the classifier function reads each letter's address and decides which mailbox it goes into. The address is the key; letters with the same address go into the same box.

Basic Syntax

Collectors.groupingBy(classifierFunction)

The classifier function has the signature Function<T, K> where:

  • T is the type of stream elements
  • K is the type of the resulting Map keys

Simple Example

List<String> words = List.of("apple", "ant", "banana", "bear", "cat");

Map<Character, List<String>> grouped = words.stream()
    .collect(Collectors.groupingBy(word -> word.charAt(0)));

// Result: {a=[apple, ant], b=[banana, bear], c=[cat]}

Here, word -> word.charAt(0) is the classifier function. It extracts the first character, so all words starting with 'a' get grouped under key 'a', all words starting with 'b' under key 'b', and so on.

The Classifier's Role

The classifier function is called for every element in the stream. Whatever value it returns becomes the Map key for that element. Elements producing the same key end up in the same List value.

Key Takeaway: The classifier function in groupingBy() determines the grouping key for each element, organizing your stream into a Map where each key maps to all elements that produced that key.