Java Reference
In-Depth Information
Recall that the
toCollection()
method takes a
Supplier
as an argument that is used to collect the data. In this
case, you have used the constructor reference
TreeSet::new
as the
Supplier
. This has an effect of using a
TreeSet
,
which is a sorted set, to collect the data.
You can also sort the list of names using the sorted operation. The
sorted()
method of the
Stream
interface
produces another stream containing the same elements on a sorted order. The following snippet of code shows how
to collect sorted names in a list:
List<String> sortedName = Person.persons()
.stream()
.map(Person::getName)
.sorted()
.collect(Collectors.toList());
System.out.println(sortedName);
[Chris, Donna, Jeff, Ken, Laynie, Li]
Note that the code applies the sorting before it collects the names. The collector notices that it is collecting an
ordered stream (sorted names) and preserves the ordering during the collection process.
You will find many static methods in the
Collectors
class that return a
Collector
meant to be used as a nested
collector. One of these methods is the
counting()
method that returns the number of input elements. Here is an
example of counting the number of people in the streams:
long count = Person.persons()
.stream()
.collect(Collectors.counting());
System.out.println("Person count: " + count);
Person count: 6
You may argue that you could have achieved the same result using the
count()
method of the
Stream
interface
as follows:
long count = Person.persons()
.stream()
.count();
System.out.println("Persons count: " + count);
Persons count: 6
When do you use the
Collectors.counting()
method instead of the
Stream.count()
method to count the number
of elements in a stream? As mentioned before, collectors can be nested. You will see examples of nested collectors
shortly. These methods in the
Collectors
class are meant to be used as nested collectors, not in this case just to count
the number of elements in the stream. Another difference between the two is their type: the
Stream.count()
method
represents an operation on a stream whereas the
Collectors.counting()
method returns a
Collector
. Listing 13-7
shows the complete program to collect sorted names in a list.