Java Reference
In-Depth Information
To fix the error, the target type of the method reference Integer::sum should be a functional interface whose
abstract method takes two int arguments and returns an int . Using a BiFunction<Integer, Integer, Integer> as
the target type will work. The following snippet of code shows how to use a method reference Integer::sum as well as
the equivalent lambda expression:
// Uses a lambda expression
BiFunction<Integer, Integer, Integer> func1 = (x, y) -> Integer.sum(x, y) ;
System.out.println(func1.apply(17, 15));
// Uses a method reference
BiFunction<Integer, Integer, Integer> func2 = Integer::sum ;
System.out.println(func2.apply(17, 15));
32
32
Let's try using a method reference of the overloaded static method valueOf() of the Integer class. The method
has three versions:
static Integer valueOf(int i)
static Integer valueOf(String s)
static Integer valueOf(String s, int radix)
The following snippet of code shows how different target types will use the three different versions of the
Integer.valueOf() static method. It is left as an exercise for readers to write the following snippet of code using
lambda expressions:
// Uses Integer.valueOf(int)
Function<Integer, Integer> func1 = Integer::valueOf ;
// Uses Integer.valueOf(String)
Function<String, Integer> func2 = Integer::valueOf ;
// Uses Integer.valueOf(String, int)
BiFunction<String, Integer, Integer> func3 = Integer::valueOf ;
System.out.println(func1.apply(17));
System.out.println(func2.apply("17"));
System.out.println(func3.apply("10001", 2));
17
17
17
The following is the last example in this category. The Person class, shown in Listing 5-12, contains a
getPersons() static method that has a declaration as shown:
static List<Person> getPersons()
 
Search WWH ::




Custom Search