Method reference lets you create a lambda expression from an existing method implementation. In method reference, the target reference is placed before the delimiter :: and the name of the method is provided after it. No brackets are needed because you are not actually calling the method. It is a syntactic sugar for lambdas.
-
A method reference to a static method. (method
parseIntofInteger, writtenIntger :: parseInt) -
A method reference to an instance method of an arbitrary type ( method
lengthof aString, writtenString::length). You're referring to a method to an object that will be supplied as one of the parameters of the lambda. -
A method reference to an instance method of an existing object. You're calling a method in a lambda to an external object that already exists. (For eg. the lambda expression
() -> expensiveTransaction.getValue()can be rewritten asexpensiveTransaction::getValue).
You can create a reference to an existing constructor using its name and the keyword new as follows: ClassName::new. It works similarly to a reference to a static method.
Supplier<Apple> c1 = Apple::new;
Apple a1 = c1.get();which is equivalent to
Supplier<Apple> c1 = () -> new Apple();
Apple a1 = c1.get();Lambda expressions provide methods that allow composition through which we can combine several simple lambda expression to build more complicated ones.
The Predicate interface includes three methods that let you reuse an existing Predicate to create more complicated ones: negate, and, and or.
The Function interface comes with two default methods for this, andThen and compose, which both return and instance of Function.
