Java 25 (LTS) reference · Stream API
Java Collectors.groupingBy() Method
Group elements into a Map by a key function, optionally counting or summing each group.
Java 25 (LTS) Since Java 8
Syntax
stream.collect(Collectors.groupingBy(classifier, downstream))
Parameters
| Parameter | Description |
|---|---|
classifierFunction<T, K> |
Computes each element's group key. |
downstream optionalCollector |
What to collect per group, e.g. counting(). |
Return value
A Map<K, List<T>> (or the downstream result).
Examples
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("tea", "mug", "kettle", "cup", "spoon");
Map<Integer, List<String>> byLength = words.stream().collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
System.out.println(byLength);
}
}
Output
{3=[tea, mug, cup], 5=[spoon], 6=[kettle]}Run this on your computer — see “Get Started” for setup.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
record Order(String customer, double total) {}
List<Order> orders = List.of(new Order("ana", 20), new Order("ben", 5), new Order("ana", 7.5));
Map<String, Long> counts = orders.stream().collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.counting()));
Map<String, Double> totals = orders.stream().collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.summingDouble(Order::total)));
System.out.println(counts);
System.out.println(totals);
}
}
Output
{ana=2, ben=1}
{ana=27.5, ben=5.0}Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
map.computeIfAbsent()· Return the value for a key, creating and storing it with a function first if the key is missing. Ideal for grouping.map.merge()· Combine a value into the map: insert it if the key is missing, otherwise apply a function to the old and new values.- Java Streams · tutorial