Back
Close

Java Collectors

[CG]jupoulton
2,001 views

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 java.util.stream.Collectors;.

Using a built-in Collector

Basic use of a Collector
// { autofold
package com.yourself;
import java.util.stream.Stream;
import java.util.List;
// }
//toList is a static function which returns a brand new Collector
import static java.util.stream.Collectors.toList;
public class Builtin {
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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
// { autofold
package com.yourself;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants