Java Reference
In-Depth Information
Predicate < String > p = s -> s . equalsIgnoreCase ( search );
Predicate < String > combined = p . or ( s -> s . equals ( "leopard" ));
String pride = cats . stream ()
. filter ( combined )
. collect ( Collectors . joining ( ", " ));
System . out . println ( pride );
Note that the Predicate<String> object p must be explicitly created, so that the
defaulted or() method can be called on it and the second lambda expression (which
will also be automatically converted to a Predicate<String> ) passed to it.
The map idiom in Java 8 makes use of a new interface Function<T, R> in the pack‐
age java.util.function . Like Predicate<T> , this is a functional interface, and so
only has one nondefaulted method, apply() . The map idiom is about transforming
a collection of one type in a collection of a potentially different type. This shows up
in the API as the fact that Function<T, R> has two separate type parameters. The
name of the type parameter R indicates that this represents the return type of the
Let's look at a code example that uses map() :
List < Integer > namesLength = cats . stream ()
. map ( String: : length )
. collect ( Collectors . toList ());
System . out . println ( namesLength );
The map and filter idioms are used to create one collection from another. In lan‐
guages that are strongly functional, this would be combined with requiring that the
original collection was not affected by the body of the lambda as it touched each
element. In computer science terms, this means that the lambda body should be
“side-effect free.”
In Java, of course, we often need to deal with mutable data, so the new Collections
API provides a way to mutate elements as the collection is traversed—the for
Each() method. This takes an argument of type Consumer<T> , that is a functional
interface that is expected to operate by side effects (although whether it actually
mutates the data or not is of lesser importance). This means that the signature of
lambdas that can be converted to Consumer<T> is (T t) → void . Let's look at a
quick example of forEach() :
List < String > pets =
Arrays . asList ( "dog" , "cat" , "fish" , "iguana" , "ferret" );
pets . stream (). forEach ( System . out :: println );
In this example, we are simply printing out each member of the collection. How‐
ever, we're doing so by using a special kind of method reference as a lambda expres‐
sion. This type of method reference is called a bound method reference , as it involves
Search WWH ::

Custom Search