Java Reference
In-Depth Information
Original strings: [Red, orange, Yellow, green, Blue, indigo, Violet]
strings in uppercase: [RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET]
strings greater than m sorted ascending: [orange, Red, Violet, Yellow]
strings greater than m sorted descending: [Yellow, Violet, Red, orange]
Fig. 17.7
|
Demonstrating lambdas and streams with an array of
String
s. (Part 2 of 2.)
Lines 18-21 display the
String
s in uppercase letters. To do so, line 19 creates a
Stream<String>
from the array
strings
, then line 20 calls
Stream
method
map
to map
each
String
to its uppercase version by calling
String
instance method
toUpperCase
.
String::toUpperCase
is known as a
method reference
and is a shorthand notation for a
lambda expression—in this case, for a lambda expression like:
(String s) -> {
return
s.toUpperCase();}
or
s -> s.toUpperCase()
String::toUpperCase
is a method reference for
String
instance method
toUpperCase
.
Figure 17.8 shows the four method reference types.
Lambda
Description
String::toUpperCase
Method reference for an instance method of a class. Creates a one-
parameter lambda that invokes the instance method on the lambda's
argument and returns the method's result. Used in Fig. 17.7.
System.out::println
Method reference for an instance method that should be called on a spe-
cific object. Creates a one-parameter lambda that invokes the instance
method on the specified object—passing the lambda's argument to the
instance method—and returns the method's result. Used in Fig. 17.10.
Math::sqrt
Method reference for a
static
method of a class. Creates a one-parame-
ter lambda in which the lambda's argument is passed to the specified a
static
method and the lambda returns the method's result.
TreeMap::new
Constructor reference. Creates a lambda that invokes the no-argument
constructor of the specified class to create and initialize a new object of
that class. Used in Fig. 17.17.
Fig. 17.8
|
Types of method references.
Stream
method
map
receives as an argument an object that implements the functional
interface
Function
—the instance method reference
String::toUpperCase
is treated as a
lambda that implements interface
Function
. This interface's
apply
method receives one
parameter and returns a result—in this case, method
apply
receives a
String
and returns
the uppercase version of the
String
. Line 21
collects
the results into a
List<String>
that
we output as a
String
.