Java Reference
In-Depth Information
Listing 2-20. Lambdas Made from Static Methods
IntFunction<String> intToString = Integer::toString;
ToIntFunction<String> parseInt = Integer::valueOf;
Making Constructors into Lambdas
Constructors live in that weird realm between static methods and instance methods: they are static methods
whose implementation acts on an instance. Depending on where you are looking, they could be called
"new , " "<init> , " or share their name with the class. Getting a method reference to a constructor is the same
as getting a method reference to a static method: just use "new" as the name of the method. From the user's
standpoint, it's really that simple. However, many classes have multiple constructors, so type inference does
a lot of heavy lifting here. See Listing 2-22 for an example of BigInteger 's String constructor as a Function .
Listing 2-21. Lambdas Made from a Constructor
Function<String,BigInteger> newBigInt = BigInteger::new;
Making Instance Methods into Lambdas
The most interesting and clever method reference is the instance method reference: you can literally
package up any object and pass its method call around. That object can then fall out of scope, but its
method is still available for use by way of this lambda. In Listing 2-22, we show a variety of different kinds
of instance method references. In print , we use a static field reference to construct the method reference.
For makeGreeting , we are using a String constant value. Both lookup and randomInt demonstrate a clever
way to have a variable that is only accessible through the lambda: in the case of lookup , it is the return value
of a method; in the case of randomIt , the object is constructed inline; resolvePath works off the base field
value; the compareAgainst method uses the argument to generate a method reference. In all these cases,
the instance is captured when the lambda is created. This means that if base is reassigned, for instance,
resolvePath will still resolve against the previous base . Also, randomInt always acts on the exact same
Random instances, no matter how many times it is called. Using instance methods this way allows you to
configure an object, and then use a key piece of functionality provided by that object without worrying that
someone will mess with the configuration.
Listing 2-22. Lambdas Made from an Instance Method
Consumer<String> print = System.out::println;
UnaryOperator<String> makeGreeting = "Hello, "::concat;
IntFunction<String> lookup = Arrays.asList("a","b","c")::get;
IntSupplier randomInt = new Random()::nextInt;
Path base = Paths.get(".");
Function<String,Path> resolvePath = base::resolve;
public IntUnaryOperator compareAgainst(Integer compareLeft) {
return compareLeft::compareTo;
}
 
Search WWH ::




Custom Search