Java groupingBy and partitioningBy: Grouping Stream Elements
Group Java stream elements with Collectors.groupingBy and split them in two with partitioningBy. Covers classifier functions, choosing TreeMap or EnumMap, why partitioningBy always has both keys, the null-key error and groupingByConcurrent for parallel streams.
kvi5hnuCode Sprout team member7 min readOn this page
In the previous article, building "all languages per country" with toMap took a singleton set per element and a hand-written union merge. Forming groups of elements that share a property is so common that the Collectors class supports it directly with groupingBy. For the special case of splitting elements into two groups by a yes/no test, there's partitioningBy.
groupingBy
groupingBy takes a classifier function. The function is applied to each element, and its result becomes the element's group key. The collector returns a map from each key to the list of elements with that key:
Map<String, List<Locale>> countryToLocales = locales.collect(
Collectors.groupingBy(Locale::getCountry));
List<Locale> swissLocales = countryToLocales.get("CH"); // [de_CH, fr_CH, it_CH]
A quick refresher on locales: a locale combines a language code (en) and usually a country code (US). en_US is English in the United States and en_IE is English in Ireland. Switzerland has German, French and Italian locales, and Ireland has English and Irish (ga_IE). Part 7 covers locales properly.
A few things to know about the result:
- Elements within each list keep their encounter order.
- A key that no element produced simply isn't in the map, so
get("JP")returnsnull. UsegetOrDefault(key, List.of())when that's inconvenient. - The map type isn't specified. Today it's a
HashMap, so the order of the keys is arbitrary. - Neither the map nor the lists are promised to be modifiable, so don't change them afterwards.
Choosing the map
The three-argument form groupingBy(classifier, mapFactory, downstream) lets you pick the map implementation. You must also pass a downstream collector. To keep plain lists, use Collectors.toList():
TreeMap<Integer, List<String>> byLength = words.collect(
Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
A TreeMap gives sorted keys and extras like firstEntry(). For enum keys, () -> new EnumMap<>(Kind.class) is compact, fast and iterates in the enum's declaration order.
Null keys
If the classifier returns null for any element, groupingBy throws a NullPointerException with the message element cannot be mapped to a null key. Map missing values to a real key first, such as an "unknown" string or a dedicated enum constant.
partitioningBy
When the classifier is a predicate, a function returning boolean, the elements fall into exactly two groups. partitioningBy handles this case:
Map<Boolean, List<Locale>> englishAndOtherLocales = locales.collect(
Collectors.partitioningBy(l -> l.getLanguage().equals("en")));
List<Locale> englishLocales = englishAndOtherLocales.get(true);
Why not groupingBy with a boolean classifier? It would work, but there are two differences:
partitioningByreturns a special two-entry map that always contains both keys,trueandfalse, even when one group is empty.groupingByleaves out a key no element produced, soget(true)could returnnull.- The two-slot map is simpler and more efficient than a general hash map.
Like groupingBy, partitioningBy accepts a downstream collector as a second argument, for example partitioningBy(pred, counting()) to count the matches and non-matches in one pass.
groupingByConcurrent
Just as toConcurrentMap mirrors toMap, groupingByConcurrent returns a ConcurrentMap that all threads of a parallel stream fill at once, instead of building separate maps and merging them. Within each group, elements are no longer in encounter order. That's fine when you only count or sum the groups, but not when you need the original order. There is no concurrent version of partitioningBy.
A complete example
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class Solution {
enum Kind { FRUIT, VEGETABLE, GRAIN }
record Food(String name, Kind kind, int calories) {}
static List<Food> foods() {
return List.of(new Food("apple", Kind.FRUIT, 52), new Food("rice", Kind.GRAIN, 130),
new Food("carrot", Kind.VEGETABLE, 41), new Food("banana", Kind.FRUIT, 89),
new Food("oats", Kind.GRAIN, 389), new Food("spinach", Kind.VEGETABLE, 23),
new Food("cherry", Kind.FRUIT, 50));
}
static Stream<Locale> locales() {
return Stream.of(Locale.of("de", "DE"), Locale.of("de", "CH"), Locale.of("fr", "CH"),
Locale.of("it", "CH"), Locale.of("fr", "FR"), Locale.of("en", "US"), Locale.of("en", "IE"),
Locale.of("ga", "IE"));
}
public static void main(String[] args) {
// group locales by country code
Map<String, List<Locale>> countryToLocales = locales()
.collect(Collectors.groupingBy(Locale::getCountry));
System.out.println("CH: " + countryToLocales.get("CH"));
System.out.println("IE: " + countryToLocales.get("IE"));
System.out.println("JP: " + countryToLocales.get("JP"));
// group by an enum, values keep encounter order
Map<Kind, List<Food>> byKind = foods().stream().collect(Collectors.groupingBy(Food::kind));
new TreeMap<>(byKind).forEach((k, v) -> System.out.println(k + " -> " + v.stream().map(Food::name).toList()));
// choose the map type: sorted keys
TreeMap<Integer, List<String>> byLength = Stream.of("fig", "kiwi", "pear", "plum", "lime", "date", "melon")
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
System.out.println("by length: " + byLength);
System.out.println("shortest group: " + byLength.firstEntry());
// EnumMap for enum keys
Map<Kind, List<Food>> enumMap = foods().stream()
.collect(Collectors.groupingBy(Food::kind, () -> new EnumMap<>(Kind.class), Collectors.toList()));
System.out.println("map type: " + enumMap.getClass().getSimpleName() + ", keys " + enumMap.keySet());
// partitioningBy always has both keys
Map<Boolean, List<String>> englishOrNot = locales()
.collect(Collectors.partitioningBy(l -> l.getLanguage().equals("en"),
Collectors.mapping(Locale::toString, Collectors.toList())));
System.out.println("English: " + englishOrNot.get(true) + ", others: " + englishOrNot.get(false));
Map<Boolean, List<Food>> heavy = foods().stream().collect(Collectors.partitioningBy(f -> f.calories() > 1000));
System.out.println("partitioningBy with no matches: true=" + heavy.get(true)
+ ", false has " + heavy.get(false).size() + " foods");
Map<Boolean, List<Food>> grouped = foods().stream().collect(Collectors.groupingBy(f -> f.calories() > 1000));
System.out.println("groupingBy with a boolean classifier: keys " + grouped.keySet());
// a null key is an error
try {
Stream.of("a", "b").collect(Collectors.groupingBy(s -> s.equals("a") ? null : s));
} catch (NullPointerException e) {
System.out.println("NullPointerException: " + e.getMessage());
}
// concurrent grouping for parallel streams
ConcurrentMap<Integer, List<Integer>> byDigits = IntStream.range(1, 2000).boxed().parallel()
.collect(Collectors.groupingByConcurrent(n -> String.valueOf(n).length()));
System.out.println("group sizes by digit count: "
+ new TreeMap<>(byDigits).entrySet().stream().map(e -> e.getKey() + "=" + e.getValue().size()).toList());
}
}
CH: [de_CH, fr_CH, it_CH]
IE: [en_IE, ga_IE]
JP: null
FRUIT -> [apple, banana, cherry]
VEGETABLE -> [carrot, spinach]
GRAIN -> [rice, oats]
by length: {3=[fig], 4=[kiwi, pear, plum, lime, date], 5=[melon]}
shortest group: 3=[fig]
map type: EnumMap, keys [FRUIT, VEGETABLE, GRAIN]
English: [en_US, en_IE], others: [de_DE, de_CH, fr_CH, it_CH, fr_FR, ga_IE]
partitioningBy with no matches: true=[], false has 7 foods
groupingBy with a boolean classifier: keys [false]
NullPointerException: element cannot be mapped to a null key
group sizes by digit count: [1=9, 2=90, 3=900, 4=1000]
The HashMap from the plain groupingBy(Food::kind) is copied into a TreeMap before printing, so the output order is stable across runs.
Common questions
How do I group by two properties, such as city and kind?
Either nest collectors, groupingBy(Shop::city, groupingBy(Shop::kind)), which gives a map of maps, or group by a combined key. A record is the cleanest combined key: record CityKind(String city, String kind) {} and groupingBy(s -> new CityKind(s.city(), s.kind())). Records implement equals and hashCode, so they work as map keys; List.of(city, kind) also works in a pinch.
How do I keep the groups in the order they first appear?
Pass LinkedHashMap::new as the map factory: groupingBy(classifier, LinkedHashMap::new, toList()).
How do I sort the groups by their size?
Group first, then sort the entries: groups.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue().size())). If you only need the sizes, group with counting() (next article) and sort by Map.Entry.comparingByValue().
What if I need more than two partitions, such as small, medium and large?
Use groupingBy with a classifier that returns an enum, groupingBy(o -> o.total() < 100 ? Size.SMALL : o.total() < 1000 ? Size.MEDIUM : Size.LARGE), and an EnumMap factory if you want all keys in declaration order. Unlike partitioningBy, missing groups are then simply absent.
Can I modify the lists in the result?
The specification makes no promise, so treat them as read-only. If you need mutable groups, ask for them with groupingBy(classifier, toCollection(ArrayList::new)).
Is groupingBy efficient for large data?
It is a single pass with one hash lookup per element, so it is linear in the number of elements. Memory grows with the result, because every element is stored in some group. For huge data sets that only need aggregates, use a downstream collector such as counting() or summingLong, so that elements are not kept.
API reference
java.util.stream.Collectors
| Method | Description |
|---|---|
groupingBy(Function<? super T, ? extends K> classifier) | a map from each classifier result to the list of elements with that result |
groupingBy(classifier, Collector downstream) | like the above, but the group values are collected with downstream (next article) |
groupingBy(classifier, Supplier<M> mapFactory, Collector downstream) | also chooses the map type, such as TreeMap::new |
groupingByConcurrent(classifier), groupingByConcurrent(classifier, downstream), groupingByConcurrent(classifier, mapFactory, downstream) | the same, producing a ConcurrentMap filled concurrently |
partitioningBy(Predicate<? super T> predicate) | a Map<Boolean, List<T>> that always has true and false keys |
partitioningBy(predicate, Collector downstream) | the same, with the two groups collected by downstream |
Summary
groupingBy(classifier)builds a map from keys to lists of elements, preserving encounter order within each list.- Keys come out in arbitrary order. Pass a map factory such as
TreeMap::newor anEnumMapsupplier, together with a downstream collector, to control the map type. - A
nullclassifier result throwsNullPointerException. partitioningBy(predicate)always yields both thetrueand thefalsekey, even when a group is empty.groupingByConcurrentfills one shared concurrent map in parallel but gives up encounter order within groups.
Practice Questions
Group a List<String> words by their first letter. What type does the result have?
words.stream().collect(Collectors.groupingBy(w -> w.charAt(0))) returns a Map<Character, List<String>>. The char result is boxed to Character.
Why might map.get(true) return null after groupingBy(n -> n > 100), but never after partitioningBy(n -> n > 100)?
If no element is greater than 100, groupingBy never creates the true key. partitioningBy always creates both keys, so get(true) returns an empty list in that case.
How do you group employees by department so that the departments are listed alphabetically?
Use the three-argument form with a TreeMap: employees.stream().collect(Collectors.groupingBy(Employee::department, TreeMap::new, Collectors.toList())).
Your classifier is Person::middleName, and some people have none (null). What happens, and how can you fix it?
groupingBy throws NullPointerException: element cannot be mapped to a null key. Map the nulls to a real key, for example p -> Objects.requireNonNullElse(p.middleName(), "").
When is groupingByConcurrent a poor choice even for a parallel stream?
When you need the elements within each group in their original encounter order, because concurrent insertion loses that order. It also gives little benefit for small streams. It works well for large parallel streams combined with order-insensitive downstream collectors such as counting().
Previous: Java Collectors.toMap: Collecting Streams into Maps
Next: Java Downstream Collectors: counting, mapping, filtering, teeing and More
Related reading
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.