Stream Collectors Grouping By

Group and partition streams with Collectors for functional data aggregation.

JavaData Integrity

Code

javasnippet
14 lines
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;

public class StreamGroup {
    public static void main(String[] args) {
        var users = List.of(new User("Alice", "eng", 30), new User("Bob", "sales", 25));
        var byDept = users.stream().collect(groupingBy(User::dept, counting()));
        var partitioned = users.stream().collect(partitioningBy(u -> u.age() > 28));
        var avgAge = users.stream().collect(averagingInt(User::age));
        System.out.println(byDept + " " + partitioned + " " + avgAge);
    }
}
record User(String name, String dept, int age) {}

How the snippet works

The moving parts are the classes StreamGroup and User and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Statements that matter

var partitioned = users.stream().collect(partitioningBy(u -> u.age() > 28));
var byDept = users.stream().collect(groupingBy(User::dept, counting()));
var avgAge = users.stream().collect(averagingInt(User::age));

Interactive Tools for This Topic

FAQ

How do you run Stream Collectors Grouping By?
Nothing to install first — run the file and the program does the rest.