Java Reference
In-Depth Information
One of the common uses for the finisher is to return an unmodifiable view of the collected data. Here is an
example that returns an unmodifiable list of person names:
List<String> names = Person.persons()
.stream()
.map(Person::getName)
.collect(Collectors.collectingAndThen(Collectors.toList(),
result -> Collections.unmodifiableList(result) ));
System.out.println(names);
[Ken, Jeff, Donna, Chris, Laynie, Li]
The collector collects the names in a mutable list and the finisher wraps the mutable list in an unmodifiable list.
Let's take another example of using the finisher. Suppose you want to print a calendar that contains the names of
people by the month of their birth. You have already collected the list of names grouped by months of their birth. You
may not have any person having a birthday in a specific month. However, you want to print the month's name anyway
and just add “None” instead of any names. Here is the first attempt:
Map<Month,String> dobCalendar = Person.persons()
.stream()
.collect(groupingBy(p -> p.getDob().getMonth(),
mapping(Person::getName, joining(", "))));
dobCalendar.entrySet().forEach(System.out::println);
MAY=Ken, Li
DECEMBER=Chris, Laynie
JULY=Jeff, Donna
This calendar has three issues:
It is not sorted by month.
It does not include all months.
Map from the collect() method is modifiable.
You can fix all three issues by using the collector returned from the collectingAndThen() method and specifying
a finisher. The finisher will add the missing months in the map, convert the map to a sorted map, and finally, wrap
the map in an unmodifiable map. The collect() method returns the map returned from the finisher. Listing 13-13
contains the complete code.
It is modifiable. The returned
Listing 13-13. Adapting the Collector Result
// DobCalendar.java
package com.jdojo.streams;
import java.time.Month;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
 
Search WWH ::




Custom Search