Java Reference
In-Depth Information
public interface Collector<T,A,R> {
Supplier<A> supplier();
BiConsumer<A,T> accumulator();
BinaryOperator<A> combiner();
Function<A,R> finisher();
Set<Collector.Characteristics> characteristics();
}
The
Collector
interface takes three type parameters called
T
,
A
, and
R
, where
T
is the type of input elements,
A
is
the type of the accumulator, and
R
is the type of the result. The first three methods look familiar; you just used them in
the previous example. The finisher is used to transform the intermediate type A to result type
R
. The characteristics of
a
Collector
describe the properties that are represented by the constants of the
Collector.Characteristics
enum.
The designers of the Streams API realized that rolling out your own collector is too much work. They provided a
utility class called
Collectors
that provides out-of-box implementations for commonly used collectors. Three of the
most commonly used methods of the
Collectors
class are
toList()
,
toSet()
, and
toCollection()
. The
toList()
method returns a
Collector
that collects the data in a
List
; the
toSet()
method returns a
Collector
that collects
data in a
Set
; the
toCollecton()
takes a
Supplier
that returns a
Collection
to be used to collect data. The following
snippet of code collects all names of people in a
List<String>
:
List<String> names = Person.persons()
.stream()
.map(Person::getName)
.collect(Collectors.toList());
System.out.println(names);
[Ken, Jeff, Donna, Chris, Laynie, Li]
Notice that this time you achieved the same result in a much cleaner way.
The following snippet of code collects all names in a
Set<String>
. Note that a
Set
keeps only unique elements.
Set<String> uniqueNames = Person.persons()
.stream()
.map(Person::getName)
.collect(Collectors.toSet());
System.out.println(uniqueNames);
[Donna, Ken, Chris, Jeff, Laynie, Li]
The output is not in a particular order because a
Set
does not impose any ordering on its elements. You can
collect names in a sorted set using the
toCollection()
method as follows:
SortedSet<String> uniqueSortedNames= Person.persons()
.stream()
.map(Person::getName)
.collect(Collectors.toCollection(TreeSet::new));
System.out.println(uniqueSortedNames);
[Chris, Donna, Jeff, Ken, Laynie, Li]