Java Reference
In-Depth Information
Figure 3.5. Recipes for constructing method references for three
different types of lambda expressions
Note that there are also special forms of method references for constructors, array constructors,
and super-calls. Let's apply method references in a concrete example. Say you'd like to sort a
List of strings, ignoring case differences. The sort method on a List expects a Comparator as
parameter. You saw earlier that Comparator describes a function descriptor with the signature
(T, T) -> int. You can define a lambda expression that leverages the method
compareToIgnoreCase in the String class as follows (note that compareToIgnoreCase is
predefined in the String class):
List<String> str = Arrays.asList("a","b","A","B");
str.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
The lambda expression has a signature compatible with the function descriptor of Comparator.
Using the recipes described previously, the example can also be written using a method
reference as follows:
 
Search WWH ::




Custom Search