Java Reference
In-Depth Information
This has the effect of splitting up each quote into its component words, and making
one superstream out of them. We count the words by creating the object words ,
essentially “pausing” halfway through the stream pipeline, and rematerializing into a
collection to get the number of words before resuming our stream operations.
Once we've done that, we can proceed with the reduce, and add up the length of all
the words, before dividing by the number of words that we have, across the quotes.
Remember that streams are a lazy abstraction, so to perform an eager operation
(like getting the size of a collection that backs a stream) we have to rematerialize the
Streams utility default methods
Java 8 takes the opportunity to introduce a number of new methods to the Java Col‐
lections libraries. Now that the language supports default methods, it is possible to
add new methods to the Collections without breaking backward compatibility.
Some of these methods are “scaffolding methods” for the Streams abstraction. These
include methods such as Collection::stream , Collection::parallelStream , and
Collection::spliterator (which has specialized forms List::spliterator and
Set::spliterator ).
Others are “missing methods,” such as Map::remove and Map::replace . This also
includes the List::sort method, that is defined in List like this:
// Essentially just forwards to the helper method in Collections
public default void sort ( Comparator <? super E > c ) {
Collections .< E > sort ( this , c );
Also in the missing methods is Map::putIfAbsent , which has been adopted from
the ConcurrentMap interface in java.util.concurrent .
Another missing method worth noting is Map::getOrDefault , which allows the
programmer to avoid a lot of tedious null checks, by providing a value that should
be returned if the key is not found.
The remaining methods provide additional functional techniques using the inter‐
faces of java.util.function :
This method takes a Predicate and iterates internally over the collection,
removing any elements that satisfy the predicate object.
The single argument to this method is a lambda expression that takes two argu‐
ments (one of the key's type and one of the value's type) and returns void . This
is converted to an instance of BiConsumer and is applied to each key-value pair
in the map.
Search WWH ::

Custom Search