Java Reference
In-Depth Information
Finally, any actual argument to the filter method needs to match this requirement.
The code is valid because the lambda expression that we're passing also takes an Apple as
parameter and returns a boolean. Note that if the lambda expression were throwing an
exception, then the declared throws clause of the abstract method would also have to match.
3.5.2. Same lambda, different functional interfaces
Because of the idea of target typing , the same lambda expression can be associated with
different functional interfaces if they have a compatible abstract method signature. For example,
both interfaces Callable and PrivilegedAction described earlier represent functions that accept
nothing and return a generic type T. The following two assignments are therefore valid:
Callable<Integer> c = () -> 42;
PrivilegedAction<Integer> p = () -> 42;
In this case the first assignment has target type Callable<Integer> and the second assignment
has target type PrivilegedAction<Integer>.
In table 3.3 we showed a similar example; the same lambda can be used with multiple different
functional interfaces:
Comparator<Apple> c1 =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
ToIntBiFunction<Apple, Apple> c2 =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
BiFunction<Apple, Apple, Integer> c3 =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
Diamond operator
Those of you who are familiar with Java's evolution will recall that Java 7 had already
introduced the idea of types being inferred from context with generic inference using the
diamond operator (<>) (this idea can be found even earlier with generic methods). A given class
instance expression can appear in two or more different contexts, and the appropriate type
argument will be inferred as exemplified here:
List<String> listOfStrings = new ArrayList<>();
List<Integer> listOfIntegers = new ArrayList<>();
Search WWH ::




Custom Search