Collectors
Last updated
Was this helpful?
Last updated
Was this helpful?
It can be used for collecting all Stream elements into a List instance. The important thing to remember is the face that we can't assume any particular List implementation with this method. If you want to have more control over this, use toCollection instead.
eg:
It can be used for collecting all Stream elements into a Set instance.
As you probably already noticed, when using toSet and toList collectors, you can’t make any assumptions of their implementations. If you want to use a custom implementation, you will need to use the _toCollection _collector with a provided collection of your choice.
Let’s create a _Stream _instance representing a sequence of elements and collect them into a _LinkedList _instance:
_ToMap _collector can be used to collect_Stream_elements into a_Map_instance. To do this, you need to provide two functions:
keyMapper
valueMapper
_keyMapper_will be used for extracting a_Map_key from a_Stream_element, and_valueMapper_will be used for extracting a value associated with a given key.
Let’s collect those elements into a Map that stores strings as keys and their lengths as values:
Function.identity()
is just a shortcut for defining function that accepts and return the same value;
Joining collector can be used for joining Stream<String> elements.
eg:
If you want to write your Collector implementation, you need to implement Collector interface and specify its three generic parameters:
T the type of objects that will be available for collection.
A the type of a mutable accumulator object,
R the type of a final result.
Let’s write an example Collector for collecting elements into an _ImmutableSet _instance. We start by specifying the right types:
Since we need a mutable collection for internal collection operation handling, we can’t use _ImmutableSet _for this; we need to use some other mutable collection or any other class that could temporarily accumulate objects for us.
In this case, we will go on with an _ImmutableSet.Builder _and now we need to implement 5 methods:
Supplier<ImmutableSet.Builder<T>>supplier()
BiConsumer<ImmutableSet.Builder<T>, T>accumulator()
BinaryOperator<ImmutableSet.Builder<T>>combiner()
Function<ImmutableSet.Builder <T>, ImmutableSet<T>>finisher()
Set <Characteristics>characteristics()>