← Back to Advanced Java Course | Chapter 3: Functional Programming | Lesson 6 of 6

Java Collectors

What is a Collector?

A Collector is used as the terminal operation in a Stream pipeline, and its job is to accumulate the stream's elements into some final container, such as a List, a Set, or a Map, depending on which Collector you choose.

Example: What is a Collector?

java
import java.util.*;
import java.util.stream.*;
public class Main {
	public static void main(String[] args) {
		List<String> names = Stream.of("Ana", "Bob", "Cy")
			.collect(Collectors.toList());
		System.out.println(names);
	}
}

Collecting into Maps

You can accumulate stream elements directly into a Map using Collectors.toMap(), for which you must supply both a key-mapper function and a value-mapper function describing how to derive each map entry from a stream element.

Example: Collecting into Maps

java
import java.util.*;
import java.util.stream.*;
public class Main {
	public static void main(String[] args) {
		List<String> names = List.of("Ana", "Bob", "Cy");
		Map<String, Integer> lengths = names.stream()
			.collect(Collectors.toMap(name -> name, String::length));
		System.out.println(lengths);
	}
}

Grouping Data

You can group stream elements together by some shared attribute using the Collectors.groupingBy() collector, which returns a Map whose keys are the grouping categories and whose values are lists of the elements in each group.

Example: Grouping Data

java
import java.util.*;
import java.util.stream.*;
public class Main {
	public static void main(String[] args) {
		List<String> words = List.of("apple", "banana", "avocado", "blueberry");
		Map<Character, List<String>> grouped = words.stream()
			.collect(Collectors.groupingBy(w -> w.charAt(0)));
		System.out.println(grouped);
	}
}

Partitioning Data

Partitioning is a special case of grouping where the grouping key is always a boolean, splitting the data into exactly two buckets. Use Collectors.partitioningBy() with a predicate to divide stream elements into a true list and a false list in a single pass.

Example: Partitioning Data

java
import java.util.*;
import java.util.stream.*;
public class Main {
	public static void main(String[] args) {
		List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
		Map<Boolean, List<Integer>> partitioned = nums.stream()
			.collect(Collectors.partitioningBy(n -> n % 2 == 0));
		System.out.println(partitioned);
	}
}

Joining and Summarizing

You can join string elements into one delimited string using Collectors.joining(), optionally supplying a delimiter, prefix, and suffix. To compute running statistics like counts, sums, or averages instead, use a Collectors.summarizingInt()-style collector.

Example: Joining and Summarizing

java
import java.util.*;
import java.util.stream.*;
public class Main {
	public static void main(String[] args) {
		List<String> names = List.of("Ana", "Bob", "Cy");
		String joined = names.stream().collect(Collectors.joining(", ", "[", "]"));
		IntSummaryStatistics stats = names.stream()
			.collect(Collectors.summarizingInt(String::length));
		System.out.println(joined + " avg=" + stats.getAverage());
	}
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.