java8collectors
java8collectors
The strategy for this operation is provided via Collector interface implementation.
Collectors
===========
All predefined implementations can be found in the Collectors class. It’s a common
practice to use a following static import with them to leverage increased
readability:
Collectors.toCollection():
============================
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:
List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
List<String> result = givenList.stream()
.collect(toCollection(LinkedList::new))
Notice that this will not work with any immutable collections. In such case, you
would need to either write a custom Collector implementation or use
collectingAndThen.
Collectors.toMap():
====================
ToMap collector can be used to collect Stream elements into a Map instance. To do
this, we 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:
List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
Map<String, Integer> result = givenList.stream()
.collect(toMap(Function.identity(), String::length));
Note that toMap doesn’t even evaluate whether the values are also equal. If it sees
duplicate keys, it immediately throws an IllegalStateException.
In such cases with key collision, we should use toMap with another signature:
The third argument here is a BinaryOperator, where we can specify how we want
collisions to be handled.
In this case, we’ll just pick any of these two colliding values because we know
that the same strings will always have the same lengths, too.
Let’s collect Stream elements to a List instance and then convert the result into
an ImmutableList instance:
Collectors.joining():
=========================
Joining collector can be used for joining Stream<String> elements.
We can join them together by doing:
"abbcccdd"
Collectors.counting():
=======================
Counting is a simple collector that allows simply counting of all Stream elements.
Collectors.summarizingDouble/Long/Int():
=========================================
SummarizingDouble/Long/Int is a collector that returns a special class containing
statistical information about numerical data in a Stream of extracted elements.
Collectors.averagingDouble/Long/Int():
========================================
AveragingDouble/Long/Int is a collector that simply returns an average of extracted
elements.
We can get average string length by doing:
Collectors.summingDouble/Long/Int():
=====================================
SummingDouble/Long/Int is a collector that simply returns a sum of extracted
elements.
Collectors.maxBy()/minBy():
==============================
MaxBy/MinBy collectors return the biggest/the smallest element of a Stream
according to a provided Comparator instance.
Collectors.groupingBy():
=========================
GroupingBy collector is used for grouping objects by some property and storing
results in a Map instance.
We can group them by string length and store grouping results in Set instances:
assertThat(result)
.containsEntry(1, newHashSet("a"))
.containsEntry(2, newHashSet("bb", "dd"))
.containsEntry(3, newHashSet("ccc"));
Notice that the second argument of the groupingBy method is a Collector and you are
free to use any Collector of your choice.
Collectors.partitioningBy()
PartitioningBy is a specialized case of groupingBy that accepts a Predicate
instance and collects Stream elements into a Map instance that stores Boolean
values as keys and collections as values.
Under the “true” key, you can find a collection of elements matching the given
Predicate, and under the “false” key, you can find a collection of elements not
matching the given Predicate.
Custom Collectors
=====================
If you want to write your Collector implementation, you need to implement Collector
interface and specify its three generic parameters:
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()
@Override
public Supplier<ImmutableSet.Builder<T>> supplier() {
return ImmutableSet::builder;
}
The accumulator() method returns a function that is used for adding a new element
to an existing accumulator object, so let’s just use the Builder‘s add method.
@Override
public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() {
return ImmutableSet.Builder::add;
}
The combiner() method returns a function that is used for merging two accumulators
together:
@Override
public BinaryOperator<ImmutableSet.Builder<T>> combiner() {
return (left, right) -> left.addAll(right.build());
}
The finisher() method returns a function that is used for converting an accumulator
to final result type, so in this case, we will just use Builder‘s build method:
@Override
public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() {
return ImmutableSet.Builder::build;
}
@Override
public Supplier<ImmutableSet.Builder<T>> supplier() {
return ImmutableSet::builder;
}
@Override
public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() {
return ImmutableSet.Builder::add;
}
@Override
public BinaryOperator<ImmutableSet.Builder<T>> combiner() {
return (left, right) -> left.addAll(right.build());
}
@Override
public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() {
return ImmutableSet.Builder::build;
}
@Override
public Set<Characteristics> characteristics() {
return Sets.immutableEnumSet(Characteristics.UNORDERED);
}