Java Reference
In-Depth Information
Suppose you have a steam of people and you want to collect the names of all of the people in an
ArrayList<String> . Here are the steps to accomplish this.
First, you need to have a supplier that will return an ArrayList<String> to store the names. You can use either of
the following statements to create the supplier:
// Using a lambda expression
Supplier<ArrayList<String>> supplier = () -> new ArrayList<>();
// Using a constructor reference
Supplier<ArrayList<String>> supplier = ArrayList::new;
Second, you need to create an accumulator that receives two arguments. The first argument is the container
returned from the supplier, which is the ArrayList<String> in this case. The second argument is the element of the
stream. Your accumulator should simply add the names to the list. You can use either of the following statements to
create an accumulator:
// Using a lambda expression
BiConsumer<ArrayList<String>, String> accumulator = (list, name) -> list.add(name);
// Using a constructor reference
BiConsumer<ArrayList<String>, String> accumulator = ArrayList::add;
Finally, you need a combiner that will combine the results of two ArrayList<String> s into one ArrayList<String> .
Note that the combiner is used only when you collect the results using a parallel stream. In a sequential stream, the
accumulator is sufficient to collect all results. Your combiner will be simple; it will add all the elements of the second list
to the first list using the addAll() method. You can use either of the following statements to create a combiner:
// Using a lambda expression
BiConsumer<ArrayList<String>, ArrayList<String>> combiner =
(list1, list2) -> list1.addAll(list2);
// Using a constructor reference
BiConsumer<ArrayList<String>, ArrayList<String>> combiner = ArrayList::addAll;
Now you are ready to use the collect() method to collect the names of all people in a list using the following
snippet of code:
List<String> names = Person.persons()
.stream()
.map(Person::getName)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
System.out.println(names);
[Ken, Jeff, Donna, Chris, Laynie, Li]
You can use a similar approach to collect data in a Set and a Map . It seems to be a lot of plumbing just to collect
data in a simple collection like a list. Another version of the collect() method provides a simpler solution. It takes an
instance of the Collector interface as an argument and collects the data for you. The Collector interface is the
java.util.stream package and it is declared as follows. Only abstract methods are shown.
 
Search WWH ::




Custom Search