Method Reference in Java 8

In the place of an anonymous class we can use Lambda expression but Sometimes, the lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by its name.

List<String> digits = Arrays.asList("1","2","3","4","5","6","7","8");
List<Integer> numbers = map(n -> new Integer(n), digits); 

Method references enable you to do this; A method reference is a shorthand syntax for a lambda expression that executes only ONE method. We can Use it if we need to declare fields or additional methods.

Object :: methodName

List<String> digits = Arrays.asList("1","2","3","4","5",”6”,”7”,”8”);
List<Integer> numbers = map(Integer::new, digits); 

Note:

  • In the place of an anonymous class we can use Lambda Expression,
  • In the place of a lambda expression where it calls only one method on that time we can use Method Reference.

Basically, Lambdas interface can contain only a single abstract method. It will fail as your interface contains more than one abstract method. In such cases anonymous classes will be most significant to use.

In java 8, anonymous classes can be use use directly by using new java 8 type annotation:

@MyTypeAnnotation InterfaceName(){}; 

Anonymous classes can be directly annotated with the new Java 8 Type Annotations,
for example:
new @MyTypeAnnotation SomeInterface(){};

There are four types of method references in Java 8:

Types Syntax Example (Using Lambda expression) Example (Using Method Reference)
Reference to a static method ContainingClass::staticMethodName s-> String.lastIndexOf(s) String::lastIndexOf
Reference to an instance method of a particular object containingObject::instanceMethodName () -> “value”.toString()  v:toString
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName s -> s.toString() String::toString()
Reference to a constructor ClassName::new   String::new () -> new String()

Leave a Reply

Your email address will not be published. Required fields are marked *