Sub topic 13
Grouping and Partitioning Data
You already know how to collect a stream into one list. Sometimes you want several smaller groups instead. For example, you might want words sorted into buckets by length, or numbers split into "big" and "small". The Collectors class has two tools for this job.
Key Terms
- Grouping puts elements into buckets based on a key. Each bucket is a list in a
Map. - Classifier is the function that picks the key for each element, such as
String::length. - Partitioning is a special kind of grouping with exactly two buckets:
trueandfalse. - Downstream collector is a second collector that decides what each bucket holds. It can hold a list, a count, or something else.
How Grouping Works
Collectors.groupingBy calls the classifier on each element. Elements that get the same key land in the same bucket.
A Worked Example
This program groups words, counts each group, and splits the words into two parts.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class GroupingExample {
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]}
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}
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]}
}
}Here is what each part does:
String::lengthis the classifier. It turns each word into its length.TreeMap::newtells Java which kind of map to build. ATreeMapkeeps its keys in sorted order, so the output is easy to read.Collectors.toList()is the downstream collector in the first call. Each bucket holds a list of words.Collectors.counting()swaps the lists for counts. The count is aLong, so the map type isMap<Integer, Long>.partitioningBytakes a predicate, which is a test that returnstrueorfalse. Words longer than four letters go in thetruebucket.
Grouping or Partitioning?
| Need | Use | Keys in result |
|---|---|---|
| Many groups by some value | `groupingBy` | Any type you choose |
| Two groups from a yes/no test | `partitioningBy` | `true` and `false` |
partitioningBy always gives you both keys, even when a bucket is empty. groupingBy only creates keys that actually appear in the data.
Exercise
Given List.of("ant", "bee", "cat", "ape"), write a collect call that maps each first letter to how many words start with it, and say what it prints when you use TreeMap::new.
Show answer
words.stream().collect(Collectors.groupingBy(w -> w.charAt(0), TreeMap::new, Collectors.counting())) prints {a=2, b=1, c=1}. The keys are Character values, and the counts are Long values.
Exercise
What does partitioningBy(n -> n > 100) return for List.of(1, 2, 3)?
Show answer
{false=[1, 2, 3], true=[]}. partitioningBy always includes both keys, even when one list is empty.