Method Reference
Recipe
// Lambda(args) -> ClassName.staticMethod(args)// Method ReferenceClassName::staticMethod
// Lambda(arg0, rest) -> arg0.instanceMethod(rest)// Method ReferenceClassName::instanceMethod
// Lambda(args) -> expr.instanceMethod(args)// Method Referenceexpr::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 SupplierSupplier<Apple> c1 = Apple::new; Apple a1 = c1.get();
// one-argument constructor, which fits the signature of the FunctionFunction<Integer, Apple> c2 = Apple::new; Apple a2 = c2.apply(128);// e.g., passing a constructor reference to the map methodList<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 BiFunctionBiFunction<Color, Integer, Apple> c3 = Apple::new;Apple a3 = c3.apply(GREEN, 128);
// create your own constructor reference for a three-argument constructorpublic interface TriFunction<T, U, V, R> { R apply(T t, U u, V v);}// use the constructor reference as followsTriFunction<Integer, Integer, Integer, RGB> colorFactory = RGB::new;