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.

[code lang=”java”] List digits = Arrays.asList(1,2,3,4,5,6,7,8);
List numbers = map(new Integer(n), digits);

[/code]

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.

Syntax :   Object :: methodName
[code lang=”java”]

List digits = Arrays.asList(1,2,3,4,5,6,7,8);
List numbers = map(Integer::new, digits);
[/code]

 

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 directly by using new java 8 type annotation:
    @MyTypeAnnotation InterfaceName() {};

There are four types of method references in Java 8:

  1. Reference to a static method,
  2. Reference to an instance method of a particular object,
  3. Reference to an instance method of an arbitrary object of a particular type,
  4. Reference to a constructor.

 

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()

 

One thought on “Method Reference in Java 8”

  1. Amarnath mishra says:

    Vikash sir,

    Very good article.Easy to understand.So much helpful.please keep posting such awesome articles to your blog.

    Regards,
    Lycan

Leave a Reply