Mastering Java Stream Collectors: Practical Examples and Code Walkthrough

This article provides a hands‑on guide to Java 8 Stream Collectors, demonstrating how to use toList, toSet, toCollection, toMap, summingInt, joining, groupingBy, partitioningBy and related collectors with clear code examples and output results.

FunTester
FunTester
FunTester
Mastering Java Stream Collectors: Practical Examples and Code Walkthrough

Overview

Collectors is a public final class that extends Object. All its methods are static and provide useful reduction operations such as accumulating elements into collections or summarizing data.

Preparation

Define a simple FunTester class with fields id, name, age, title, and size, plus a constructor, getters, setters and toString. Create a List<FunTester> and add five sample objects.

List<FunTester> funs = new ArrayList<>();
funs.add(new FunTester(1, "1号", 10, "机器人", 1.1));
funs.add(new FunTester(2, "2号", 20, "机器人", 2.2));
funs.add(new FunTester(3, "3号", 30, "背锅侠", 3.3));
funs.add(new FunTester(4, "4号", 40, "BUG君", 4.4));
funs.add(new FunTester(5, "5号", 50, "菜鸟", 5.5));

Stream.collect() Basics

The collect() method is the most powerful Stream operation. Its signature is

<R, A> R collect(Collector<? super T, A, R> collector)

. It folds stream elements into a mutable container defined by a Collector.

Collectors.toList()

Collect all names into a List<String>:

List<String> names = funs.stream()
    .map(f -> f.name)
    .collect(Collectors.toList());
output(names);

Output shows each name in insertion order.

Collectors.toSet()

Collect distinct titles into a Set<String> (duplicates are removed):

Set<String> titles = funs.stream()
    .map(f -> f.title)
    .collect(Collectors.toSet());
output(titles);

The set is unordered.

Collectors.toCollection()

Collect names into a specific collection type, e.g., LinkedList:

LinkedList<String> names = funs.stream()
    .map(f -> f.name)
    .collect(Collectors.toCollection(LinkedList::new));

Collectors.toMap()

Convert the stream into a Map where the key is id and the value is name. The most complete overload requires key mapper, value mapper, merge function, and map supplier.

HashMap<Integer, String> map = funs.stream()
    .collect(Collectors.toMap(FunTester::getId,
                              FunTester::getName,
                              (v1, v2) -> v2,
                              HashMap::new));
output(map);

Collectors.summingInt()

Summarize integer fields, e.g., total age, average, count, max, and min:

IntSummaryStatistics stats = funs.stream()
    .map(FunTester::getAge)
    .collect(Collectors.summarizingInt(f -> f));
output(stats.getSum());
output(stats.getAverage());
output(stats.getCount());
output(stats.getMax());
output(stats.getMin());

Similar APIs exist for summarizingLong and summarizingDouble, and there are shortcut averaging methods.

Collectors.joining()

Concatenate elements into a single String with a delimiter, prefix, and suffix:

String joined = funs.stream()
    .map(FunTester::getTitle)
    .collect(Collectors.joining(",", "[", "]"));
output(joined);

Collectors.groupingBy()

Group stream elements by a classifier function, e.g., group titles by their length:

Map<Integer, List<String>> groups = funs.stream()
    .map(FunTester::getTitle)
    .collect(Collectors.groupingBy(String::length));
output(groups);

Collectors.partitioningBy()

Partition elements into two groups based on a predicate, such as id > 2:

Map<Boolean, List<FunTester>> partition = funs.stream()
    .collect(Collectors.partitioningBy(f -> f.getId() > 2));
output(partition.get(false));
output("----------------");
output(partition.get(true));

Collectors.toConcurrentMap()

The concurrent version works like toMap but returns a thread‑safe map; usage mirrors the previous example.

These examples illustrate the most common collectors and how they can be combined with Java 8 Stream pipelines to transform, aggregate, and organize data efficiently.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaStreamjava8FunctionalProgrammingCollectorsDataAggregation
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.