Collecting to Different Data Structures per Partition
What You'll Learn
You'll learn how to use downstream collectors with partitioningBy to gather each partition into sets, custom collections, or other specialized data structures instead of the default lists.
Beyond Default Lists
By default, partitioningBy returns a Map<Boolean, List<T>>, grouping elements into two lists based on your predicate. But just like with groupingBy, you can control what type of collection each partition uses by providing a downstream collector as a second argument.
This is useful when you need:
- Sets to eliminate duplicates within each partition
- Custom collections like
TreeSetfor sorted partitions - Other structures that better fit your domain needs
The Pattern
Collectors.partitioningBy(predicate, downstreamCollector)
The downstream collector determines how elements in each partition are collected.
Practical Examples
Collecting to Sets:
Map<Boolean, Set<String>> result =
Stream.of("apple", "banana", "apple", "cherry", "banana")
.collect(Collectors.partitioningBy(
s -> s.length() > 5,
Collectors.toSet()
));
// {false=[apple, cherry], true=[banana]}
Notice duplicates are removed within each partition.
Collecting to Custom Collections:
Map<Boolean, TreeSet<String>> sorted =
Stream.of("dog", "cat", "elephant", "ant")
.collect(Collectors.partitioningBy(
s -> s.length() > 3,
Collectors.toCollection(TreeSet::new)
));
// {false=[ant, cat, dog], true=[elephant]}
Each partition is now a sorted TreeSet.
Think of It Like Sorting Mail
Imagine sorting mail into two bins (short/long addresses). partitioningBy creates the two bins, but the downstream collector decides whether each bin is a pile (list), a sorted tray (TreeSet), or a unique-only holder (set).
Key Takeaway: Use downstream collectors like toSet() or toCollection() with partitioningBy to control the data structure of each partition, enabling duplicate removal, sorting, or custom collection behavior per partition.