Java Reference
In-Depth Information
List<String> str = Arrays.asList("a","b","A","B");
str.sort(String::compareToIgnoreCase);
Note that the compiler goes through a similar type-checking process as for lambda expressions
to figure out whether a method reference is valid with a given functional interface: the signature
of the method reference has to match the type of the context.
To check your understanding of method references, have a go at Quiz 3.6 !
Quiz 3.6: Method references
What are equivalent method references for the following lambda expressions?
1 .
Function<String, Integer> stringToInteger =
(String s) -> Integer.parseInt(s);
2 .
BiPredicate<List<String>, String> contains =
(list, element) -> list.contains(element);
Answers:
1 . This lambda expression forwards its argument to the static method parseInt of Integer. This
method takes a String to parse and returns an Integer. As a result, the lambda can be rewritten
using recipe
from figure 3.5 (lambda expressions calling a static method) as follows:
Function<String, Integer> stringToInteger = Integer::parseInt;
2 . This lambda uses its first argument to call the method contains on it. Because the first
argument is of type List, you can use recipe
from figure 3.5 as follows:
BiPredicate<List<String>, String> contains = List::contains;
This is because the target type describes a function descriptor (List<String>, String) -> boolean,
and List::contains can be unpacked to that function descriptor.
Search WWH ::




Custom Search