Java Collectors
In this page:
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?
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: