Sub topic 13
Grouping and Partitioning Data
In the previous chapters you collected stream results into lists, sets, and maps. Sometimes you need more than one flat result. You might want to sort words into buckets by their length, or split numbers into even and odd. The Collectors class has two tools for this: groupingBy and partitioningBy.
This chapter shows how both work, how to summarize each group with a downstream collector, and which edge cases can surprise you.
What Grouping Means
Grouping puts elements into buckets. You give Java a rule, and Java uses that rule to pick a bucket for each element. The rule is called a classifier. A classifier is a function that takes an element and returns a key, which is the label of its bucket.
The result is a Map. Each key in the map is a bucket label. Each value holds the elements that landed in that bucket.
Your First groupingBy
Here the classifier is String::length, so words with the same length share a bucket.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class GroupByLength {
public static void main(String[] args) {
List<String> words = List.of("apple", "bean", "cherry", "date", "fig");
Map<Integer, List<String>> byLength = words.stream()
.collect(Collectors.groupingBy(
String::length,
TreeMap::new,
Collectors.toList()));
System.out.println(byLength);
// {3=[fig], 4=[bean, date], 5=[apple], 6=[cherry]}
}
}This call to groupingBy takes three arguments:
- The classifier,
String::length, decides the key. - The map factory,
TreeMap::new, decides what kind of map to build. ATreeMapkeeps its keys in sorted order. - The downstream collector,
Collectors.toList(), decides what to do with the elements in each bucket.
You can also call groupingBy with only the classifier: Collectors.groupingBy(String::length). That version uses a HashMap and puts each bucket into a list. It gives the same buckets, but the printed order of the keys is not guaranteed.
Downstream Collectors: Summarizing Each Group
A downstream collector is a collector that runs inside each bucket. Without one, every bucket becomes a list. With one, you can turn each bucket into a count, a sum, an average, or a joined string.
The table lists the common downstream collectors.
| Downstream collector | What each bucket becomes | Example value type |
|---|---|---|
| `Collectors.toList()` | A list of the elements | `List<String>` |
| `Collectors.toSet()` | A set of the elements | `Set<String>` |
| `Collectors.counting()` | How many elements | `Long` |
| `Collectors.summingInt(f)` | The sum of `f` applied to each element | `Integer` |
| `Collectors.averagingInt(f)` | The average of `f` applied to each element | `Double` |
| `Collectors.mapping(f, c)` | Applies `f` first, then collects with `c` | depends on `c` |
| `Collectors.joining(", ")` | The elements joined into one string | `String` |
Counting per group
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class CountByLength {
public static void main(String[] args) {
List<String> words = List.of("apple", "bean", "cherry", "date", "fig");
Map<Integer, Long> countByLength = words.stream()
.collect(Collectors.groupingBy(
String::length,
TreeMap::new,
Collectors.counting()));
System.out.println(countByLength); // {3=1, 4=2, 5=1, 6=1}
}
}counting() returns a Long, not an Integer. That is why the map type is Map<Integer, Long>.
Summing and transforming per group
The next example groups fruits by their first letter. It shows two downstream collectors. summingInt adds up the letters in each group. mapping turns each fruit into upper case before collecting it.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class GroupByFirstLetter {
public static void main(String[] args) {
List<String> fruits = List.of("apple", "avocado", "banana", "blueberry", "cherry");
Map<Character, Integer> lettersPerGroup = fruits.stream()
.collect(Collectors.groupingBy(
f -> f.charAt(0),
TreeMap::new,
Collectors.summingInt(String::length)));
System.out.println(lettersPerGroup); // {a=12, b=15, c=6}
Map<Character, List<String>> upperPerGroup = fruits.stream()
.collect(Collectors.groupingBy(
f -> f.charAt(0),
TreeMap::new,
Collectors.mapping(String::toUpperCase, Collectors.toList())));
System.out.println(upperPerGroup);
// {a=[APPLE, AVOCADO], b=[BANANA, BLUEBERRY], c=[CHERRY]}
}
}The a group adds up to 12 because "apple" has 5 letters and "avocado" has 7. The charAt method returns a char. Java boxes it to Character so it can be a map key.
Partitioning: Exactly Two Groups
Partitioning is a special kind of grouping. It always makes two buckets. The rule is a predicate, which is a function that returns true or false. The result is a Map<Boolean, ...> with the key false for elements that fail the test and true for elements that pass.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class PartitionExample {
public static void main(String[] args) {
List<String> words = List.of("apple", "bean", "cherry", "date", "fig");
Map<Boolean, List<String>> longOrShort = words.stream()
.collect(Collectors.partitioningBy(w -> w.length() > 4));
System.out.println(longOrShort);
// {false=[bean, date, fig], true=[apple, cherry]}
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
Map<Boolean, Long> evenCount = numbers.stream()
.collect(Collectors.partitioningBy(
n -> n % 2 == 0,
Collectors.counting()));
System.out.println(evenCount); // {false=3, true=3}
System.out.println(longOrShort.get(true)); // [apple, cherry]
}
}Like groupingBy, partitioningBy takes an optional downstream collector as its second argument.
Edge Cases to Know
Empty input
The two collectors act differently when the stream is empty. groupingBy returns an empty map because no element created a bucket. partitioningBy always contains both keys, even when both lists are empty.
import java.util.List;
import java.util.stream.Collectors;
public class EmptyExample {
public static void main(String[] args) {
List<String> empty = List.of();
System.out.println(empty.stream()
.collect(Collectors.groupingBy(String::length))); // {}
System.out.println(empty.stream()
.collect(Collectors.partitioningBy(s -> s.length() > 3)));
// {false=[], true=[]}
}
}This means map.get(true) on a partition result never returns null. With groupingBy, map.get(key) returns null when no element produced that key. Use getOrDefault to stay safe.
Null keys
Choosing between them
| Question | Use |
|---|---|
| Do you need exactly a yes group and a no group? | `partitioningBy` |
| Can there be many groups, or is the number unknown? | `groupingBy` |
| Must both groups appear even when one is empty? | `partitioningBy` |
You could write groupingBy(n -> n % 2 == 0), but it would leave out the true or false key whenever that bucket is empty. partitioningBy is clearer and always includes both keys.
Exercise
Given List.of("cat", "cow", "dog", "duck", "eel"), write a collect call that maps each first letter to the number of words starting with it, with keys in sorted order. What does it print?
Show answer
words.stream().collect(Collectors.groupingBy(w -> w.charAt(0), TreeMap::new, Collectors.counting())) prints {c=2, d=2, e=1}.
Exercise
You partition List.of(1, 3, 5) with partitioningBy(n -> n % 2 == 0). What is printed, and how does it differ from groupingBy with the same lambda?
Show answer
partitioningBy prints {false=[1, 3, 5], true=[]}. groupingBy prints {false=[1, 3, 5]} because no element produced the true key.
Exercise
Why is the value type Long instead of Integer when you use Collectors.counting() as a downstream collector?
Show answer
Collectors.counting() always produces a Long, so each bucket's count is a Long and the map type must be Map<K, Long>.