2.8.  Develop code that uses a method reference, including refactoring a lambda expression to a method reference


Method references can be seen as shorthand for lambdas calling only a specific method. The basic idea is that if a lambda represents "call this method directly". It is best to refer to the method by name rather than by a description of how to call it. A method reference lets you create a lambda expression from an existing method implementation. By referring to a method name explicitly, your code can gain better readability.


Lambdas created from constructors are often referred to as constructor references, which are considered for exam to be a subset of method references.

When you need a method reference, the target reference is placed before the delimiter :: and the name of the method is provided after it. For example, String::toUpperCase is a method reference to the method toUpperCase defined in the String class. The method reference is shorthand for the lambda expression (String s) -> s.toUpperCase();.


Remember that no parentheses (round brackets) are needed because you are not actually calling the method.

There are four types of method reference:

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz