Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
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.
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