Java Collectors


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

What's a Collector?

A Collector is a Java construct to use in conjunction with streams in order to turn a stream into a whatever-you-like.

Built-in Collectors exist and include:

  • toList() Everything ends up in a list
  • toSet() Everything ends up in a set
  • joining(String s) Everything ends up in a string, separated by s
  • And many more along the same lines.

Where are they ? in;.

Using a built-in Collector

Basic use of a Collector
// {...}
//toList is a static function which returns a brand new Collector
import static;
public class Builtin {
public static List<Integer> filterOutSmallValues(Integer[] arrayOfInts, int minimumValue) {
List<Integer> list = null;
// Here is a nice little stream
Stream<Integer> stream = Stream.of(arrayOfInts).filter(i -> i >= minimumValue);
// We want to return a list, so we need to COLLECT the values of the stream
//list = stream.collect(/* A collector goes here. */);
// We return the result as a list
return list;

Writing your own Collector

There are many reasons why you might want to write your own Collector. Improving the readibility of a core part of your code is one of them.

Let's take a look at how to do this with an example.

Let's say you need to convert a string of space-separated integers to a list of Point instances where every two integers are X and Y coordinates.

There are a few methods to @Override when writing a new subclass of Collector. Look for every occurence of Fix me! to solve this exercice.

Writing a toPointList Collector
// {...}
public class Custom {
* @param manyInts
* is a String containing pairs of integers such as: "4 5 6 3 2 10"
* @return a list of Points using each pair of ints as coordinates: Point(x=4, y=5), Point(x=3, y=2), Point(x=2, y=10)
public static List<Point> coordStringToPoints(String manyInts) {
//First, let's turn the space-separated integers into a stream
// we can manipulate
Stream.of(manyInts.split(" "))
// Next, we parse each int
// Then we collect the ints
// It's a good idea to use a factory function to return a new Collector
public static PointListCollector toPointList() {
return new PointListCollector();

Going further

Want to learn more about Collectors now you've toyed with them a little?

Check out the official Java doc.

Check out some more advanced usage of Collectors by browsing StackOverflow

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content