Java Collectors Class

Su Suriya Ravichandran Updated 18 Nov 2026
7 min read ·Lesson 178 of 306

What Collectors Provides

java.util.stream.Collectors is a utility class full of static methods that create ready-made collectors for stream.collect(...). The previous lesson used the simple ones — toList, toSet, toMap, joining. This lesson covers the collectors that make streams a reporting tool: grouping, partitioning, counting and aggregating per group, and combining collectors.

The key idea is the downstream collector: collectors like groupingBy split the elements into groups and then apply another collector to each group — count it, sum it, average it, collect names from it, find its maximum. Downstream collectors can be nested, which lets one pipeline compute what would otherwise need several loops and temporary maps.

The examples use this data class (compile it together with each example):

import java.util.*;

public class Data {
    record Enrollment(String student, String city, String course, String level, int score, double fee, Set<String> skills) { }

    static final List<Enrollment> ALL = List.of(
        new Enrollment("Asha", "Chennai", "Java", "beginner", 91, 4999, Set.of("oop", "streams")),
        new Enrollment("Ravi", "Madurai", "Java", "beginner", 45, 4999, Set.of("oop")),
        new Enrollment("Meena", "Chennai", "Django", "intermediate", 77, 5999, Set.of("orm", "templates")),
        new Enrollment("Kumar", "Salem", "Java", "advanced", 68, 6999, Set.of("streams", "concurrency")),
        new Enrollment("Divya", "Madurai", "Docker", "intermediate", 39, 3999, Set.of("containers")),
        new Enrollment("Asha", "Chennai", "Django", "intermediate", 88, 5999, Set.of("orm")),
        new Enrollment("Priya", "Chennai", "Docker", "intermediate", 82, 3999, Set.of("containers", "compose")));
}

The examples use import static java.util.stream.Collectors.*;, so collectors can be written as groupingBy(...) instead of Collectors.groupingBy(...) — common practice for collector-heavy code.

groupingBy and Downstream Collectors

import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;

public class G1 {
    public static void main(String[] args) {
        var all = Data.ALL;
        Map<String, List<Data.Enrollment>> byCourse = all.stream().collect(groupingBy(Data.Enrollment::course));
        System.out.println("groups: " + new TreeMap<>(byCourse).keySet() + ", Java has " + byCourse.get("Java").size());

        System.out.println("count:    " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new, counting())));
        System.out.println("revenue:  " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new, summingDouble(Data.Enrollment::fee))));
        System.out.println("avg:      " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new, averagingInt(Data.Enrollment::score))));
        System.out.println("names:    " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new, mapping(Data.Enrollment::student, joining(" & ")))));
        System.out.println("passed:   " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new,
                                         filtering(e -> e.score() >= 50, mapping(Data.Enrollment::student, toList())))));
        System.out.println("skills:   " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new,
                                         flatMapping(e -> e.skills().stream(), toCollection(TreeSet::new)))));
        System.out.println("top:      " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new,
                                         collectingAndThen(maxBy(Comparator.comparingInt(Data.Enrollment::score)),
                                                           o -> o.map(Data.Enrollment::student).orElse("-")))));
        System.out.println("nested:   " + all.stream().collect(groupingBy(Data.Enrollment::city, TreeMap::new,
                                         groupingBy(Data.Enrollment::course, TreeMap::new, counting()))));
    }
}

Output:

groups: [Django, Docker, Java], Java has 3
count:    {Django=2, Docker=2, Java=3}
revenue:  {Django=11998.0, Docker=7998.0, Java=16997.0}
avg:      {Django=82.5, Docker=60.5, Java=68.0}
names:    {Django=Meena & Asha, Docker=Divya & Priya, Java=Asha & Ravi & Kumar}
passed:   {Django=[Meena, Asha], Docker=[Priya], Java=[Asha, Kumar]}
skills:   {Django=[orm, templates], Docker=[compose, containers], Java=[concurrency, oop, streams]}
top:      {Django=Asha, Docker=Priya, Java=Asha}
nested:   {Chennai={Django=2, Docker=1, Java=1}, Madurai={Docker=1, Java=1}, Salem={Java=1}}

The three forms of groupingBy

FormResult
groupingBy(classifier)Map<K, List<T>> — each key maps to the list of elements with that key (a HashMap, no key order)
groupingBy(classifier, downstream)Map<K, D> — the downstream collector is applied to each group
groupingBy(classifier, mapFactory, downstream)Same, with a chosen map type — TreeMap::new sorts the keys

The classifier is a function that computes each element's group key (Enrollment::course). Only keys that actually occur become map entries.

Downstream collectors

CollectorPer group, produces
counting()The number of elements (Long)
summingInt/Long/Double(mapper)The sum of a numeric property
averagingInt/Long/Double(mapper)The average (Double)
minBy(cmp) / maxBy(cmp)The smallest/largest element, as an Optional
mapping(mapper, downstream)Transforms each element, then collects with another collector
filtering(predicate, downstream) (Java 9+)Keeps matching elements, then collects
flatMapping(mapper, downstream) (Java 9+)Turns each element into a stream and collects all their elements
joining(...)Concatenated strings (after mapping to strings)
toList(), toSet(), toCollection(...)A collection of the group's elements
collectingAndThen(downstream, finisher)Applies a final transformation to the downstream result

Points to notice in the output:

  • mapping collects a property instead of whole objects — names per course, joined into a string.
  • filtering versus filtering the stream first: filtering(e -> e.score() >= 50, ...) keeps every course key and filters within each group. Using stream().filter(...) before grouping would make courses with no passing students disappear from the map entirely — sometimes that's wanted, often it isn't.
  • flatMapping merges the skills of all students in a course into one sorted set.
  • maxBy returns Optional because a collector can't know a group is non-empty; collectingAndThen unwraps it into the student's name.
  • Multi-level grouping: a groupingBy as the downstream of another groupingBy produces a nested map — enrollments per course within each city.

Partitioning, Statistics and Combining Collectors

import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;

public class G2 {
    public static void main(String[] args) {
        var all = Data.ALL;
        Map<Boolean, List<String>> passFail = all.stream()
            .collect(partitioningBy(e -> e.score() >= 50, mapping(Data.Enrollment::student, toList())));
        System.out.println("passed: " + passFail.get(true) + ", failed: " + passFail.get(false));
        System.out.println("empty partitions exist: " + Stream.<Integer>empty().collect(partitioningBy(n -> n > 0)));

        IntSummaryStatistics stats = all.stream().collect(summarizingInt(Data.Enrollment::score));
        System.out.println(stats.getMin() + " " + stats.getMax() + " " + stats.getAverage() + " " + stats.getCount());

        record Range(int low, int high) { }
        Range r = all.stream().collect(teeing(
            minBy(Comparator.comparingInt(Data.Enrollment::score)),
            maxBy(Comparator.comparingInt(Data.Enrollment::score)),
            (min, max) -> new Range(min.get().score(), max.get().score())));
        System.out.println(r);

        List<String> unmodifiable = all.stream().map(Data.Enrollment::course).distinct()
            .collect(collectingAndThen(toList(), Collections::unmodifiableList));
        System.out.println(unmodifiable);

        double revenue = all.stream().collect(reducing(0.0, Data.Enrollment::fee, Double::sum));
        System.out.println(revenue);

        java.util.stream.Collector<String, StringJoiner, String> bulleted = java.util.stream.Collector.of(
            () -> new StringJoiner("\n"),
            (j, s) -> j.add("  • " + s),
            StringJoiner::merge,
            StringJoiner::toString);
        System.out.println(all.stream().map(Data.Enrollment::student).distinct().sorted().collect(bulleted));
    }
}

Output:

passed: [Asha, Meena, Kumar, Asha, Priya], failed: [Ravi, Divya]
empty partitions exist: {false=[], true=[]}
39 91 70.0 7
Range[low=39, high=91]
[Java, Django, Docker]
36993.0
  • Asha
  • Divya
  • Kumar
  • Meena
  • Priya
  • Ravi
  • partitioningBy(predicate[, downstream]) is a special grouping with exactly two groups, keyed true and false. Unlike groupingBy, both keys are always present, even when a group is empty — so passFail.get(false) never returns null.
  • summarizingInt/Long/Double computes count, sum, minimum, maximum and average in one pass, as an IntSummaryStatistics object.
  • teeing(c1, c2, merger) (Java 12+) sends every element to two collectors and combines their results — here the minimum and maximum score in a single pass, packed into a local record.
  • collectingAndThen(collector, finisher) post-processes a result, e.g. wrapping a list as unmodifiable.
  • reducing(identity, mapper, op) is the collector form of map + reduce, mainly useful as a downstream collector.
  • Collector.of(supplier, accumulator, combiner, finisher) creates a custom collector: supply a container (StringJoiner), add each element, merge two containers (for parallel streams) and convert to the final result. Here it formats a bulleted list.

Grouping Results Are Maps — Choose the Map Type

Without a map factory, groupingBy returns a HashMap, whose iteration order is unpredictable. For output that people read, or that tests compare, pass TreeMap::new (sorted keys) or LinkedHashMap::new (first-occurrence order). For enum keys, () -> new EnumMap<>(Level.class) is the fastest option and keeps declaration order.

Practical Example: A Course Dashboard

An admin dashboard shows one row per course: number of students, revenue, average score, pass rate and top student — plus a few headline figures. A single groupingBy with collectingAndThen builds a complete report record for each group.

import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;

public class Dash {
    record CourseReport(String course, long students, double revenue, double average, double passRate, String topStudent) { }

    public static void main(String[] args) {
        Map<String, CourseReport> reports = Data.ALL.stream().collect(groupingBy(
            Data.Enrollment::course,
            TreeMap::new,
            collectingAndThen(toList(), list -> new CourseReport(
                list.get(0).course(),
                list.size(),
                list.stream().mapToDouble(Data.Enrollment::fee).sum(),
                list.stream().mapToInt(Data.Enrollment::score).average().orElse(0),
                100.0 * list.stream().filter(e -> e.score() >= 50).count() / list.size(),
                list.stream().max(Comparator.comparingInt(Data.Enrollment::score)).map(Data.Enrollment::student).orElse("-")))));

        System.out.printf("%-7s %8s %10s %7s %7s  %s%n", "Course", "Students", "Revenue", "Avg", "Pass%", "Top");
        reports.values().forEach(r -> System.out.printf("%-7s %8d %10.0f %7.1f %6.0f%%  %s%n",
            r.course(), r.students(), r.revenue(), r.average(), r.passRate(), r.topStudent()));

        Map<String, Double> revenueByCity = Data.ALL.stream()
            .collect(groupingBy(Data.Enrollment::city, summingDouble(Data.Enrollment::fee)));
        String best = revenueByCity.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse("-");
        Map<String, Long> repeatLearners = Data.ALL.stream()
            .collect(collectingAndThen(groupingBy(Data.Enrollment::student, counting()),
                     m -> m.entrySet().stream().filter(e -> e.getValue() > 1)
                           .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))));
        System.out.println("best city: " + best + " (" + revenueByCity.get(best) + ")");
        System.out.println("repeat learners: " + repeatLearners);
    }
}

Output:

Course  Students    Revenue     Avg   Pass%  Top
Django         2      11998    82.5    100%  Asha
Docker         2       7998    60.5     50%  Priya
Java           3      16997    68.0     67%  Asha
best city: Chennai (20996.0)
repeat learners: {Asha=2}

How it works:

  1. One group per course, sorted by name with TreeMap::new.
  2. collectingAndThen(toList(), list -> new CourseReport(...)) first collects each course's enrollments into a list, then turns that list into a report record. Inside the finisher, short streams over the group compute each column. list.get(0) is safe because groupingBy never creates empty groups.
  3. The pass rate is computed as a percentage — 100.0 * comes first so the division happens in floating point, not integer arithmetic.
  4. The report table is printed from the map's values, already in course order. %% prints a literal percent sign.
  5. Best city: revenue is summed per city, and the entry with the highest value wins.
  6. Repeat learners: students are counted, and collectingAndThen filters the resulting map to students with more than one enrollment — Asha, enrolled in both Java and Django.

Computing the same dashboard with loops would need several maps of running totals updated in one loop, or several separate loops. With collectors, each figure is declared where it's used, and the whole report is built in a single pipeline per question.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Collectors Class and get answers drawn from it.

Signed-in readers only.