Method Reference
Recipe
// Lambda
(args) -> ClassName.staticMethod(args)
// Method Reference
ClassName::staticMethod
// Lambda
(arg0, rest) -> arg0.instanceMethod(rest)
// Method Reference
ClassName::instanceMethod
// Lambda
(args) -> expr.instanceMethod(args)
// Method Reference
expr::instanceMethod
examples
ToIntFunction<String> stringToInt = (String s) -> Integer.parseInt(s);
ToIntFunction<String> stringToInt = Integer::parseInt;
BiPredicate<List<String>, String> contains =
(list, element) -> list.contains(element);
BiPredicate<List<String>, String> contains = List::contains;
Predicate<String> startsWithNumber =
(String string) -> this.startsWithNumber(string);
Predicate<String> startsWithNumber = this::startsWithNumber;
Constructor Reference
// zero-argument constructor, which fits the signature of the Supplier
Supplier<Apple> c1 = Apple::new;
Apple a1 = c1.get();
// one-argument constructor, which fits the signature of the Function
Function<Integer, Apple> c2 = Apple::new;
Apple a2 = c2.apply(128);
// e.g., passing a constructor reference to the map method
List<Integer> weights = Arrays.asList(7, 3, 2, 18);
List<Apple> apples = createApples(weights, Apple::new);
public List<Apple> createApples(List<Integer> list,
Function<Integer, Apple> f) {
List<Apple> result = new ArrayList<>();
for (Integer i : list) {
result.add(f.apply(i));
}
return result;
}
// two-argument constructor, which fits the signature of the BiFunction
BiFunction<Color, Integer, Apple> c3 = Apple::new;
Apple a3 = c3.apply(GREEN, 128);
// create your own constructor reference for a three-argument constructor
public interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}
// use the constructor reference as follows
TriFunction<Integer, Integer, Integer, RGB> colorFactory = RGB::new;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。