Simple Grouping: Grouping by Property
You'll learn how to organize stream elements into groups based on a single shared property, creating a categorized map structure.
What Is Simple Grouping?
Think of grouping like sorting mail into mailboxes by street name, or organizing books by genre. In Java Streams, groupingBy takes a collection of objects and creates a Map where each key represents a category (like "Fiction" or "Non-Fiction"), and the value is a List of all objects belonging to that category.
The classifier function you pass to groupingBy() extracts the property that determines which group each element belongs to.
How It Works
The basic pattern is:
Map<KeyType, List<ItemType>> grouped =
stream.collect(Collectors.groupingBy(item -> item.getProperty()));
The classifier function (item -> item.getProperty()) runs on each element, and its return value becomes the map key. All elements producing the same key are collected into a list under that key.
Real-World Example
List<String> fruits = List.of("apple", "banana", "apricot", "blueberry", "avocado");
// Group by first letter
Map<Character, List<String>> byFirstLetter =
fruits.stream()
.collect(Collectors.groupingBy(fruit -> fruit.charAt(0)));
// Result: {a=[apple, apricot, avocado], b=[banana, blueberry]}
You could also group employees by department, orders by status, or products by category—any property that categorizes your objects.
Why It Matters
Instead of manually looping and building maps with conditional logic, groupingBy handles the entire categorization process declaratively. The collector creates the map, initializes lists for new keys, and adds elements to the appropriate groups automatically.
Key Takeaway: Use Collectors.groupingBy() with a classifier function to transform a stream into a Map<Key, List<Value>>, where elements are automatically grouped by any property you specify.