Refinement of Java

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 stringToInt = (String s) -> Integer.parseInt(s);
ToIntFunction stringToInt = Integer::parseInt;
BiPredicate, String> contains =
                  (list, element) -> list.contains(element);
BiPredicate, String> contains = List::contains;
Predicate startsWithNumber =
           (String string) -> this.startsWithNumber(string);
Predicate startsWithNumber = this::startsWithNumber;

Constructor Reference

// zero-argument constructor, which fits the signature of the Supplier
Supplier c1 = Apple::new; 
Apple a1 = c1.get(); 
// one-argument constructor, which fits the signature of the Function
Function c2 = Apple::new; 
Apple a2 = c2.apply(128);

// e.g., passing a constructor reference to the map method
List weights = Arrays.asList(7, 3, 2, 18);
List apples = createApples(weights, Apple::new);

public List createApples(List list, 
                                Function f) {
    List 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 c3 = Apple::new;
Apple a3 = c3.apply(GREEN, 128);
// create your own constructor reference for a three-argument constructor
public interface TriFunction {
    R apply(T t, U u, V v);
}

// use the constructor reference as follows
TriFunction colorFactory = RGB::new;

你可能感兴趣的:(java)