Wednesday, 8 May 2019

Method References in Java 8

       In previous post, we learned Consumer Interface in Java 8 with examples. In this post, we will discuss another new feature of java 8, i.e method references.

      A method reference is the shorthand notation for a lambda expression to call a method. In previous versions of Java, we will use object dot method name to call method of the given object. In java 8, using :: operator after the object, to call the method.

Below is the general syntax of a method reference:

Object :: methodName

The example of Method Reference uses,

Using lambda expression,

s -> System.out.println(s)

It replaces using method reference as below,

System.out::println

Examples:-

1)  Instance method of object example(Object::instanceMethod)

MethodRefExample.java,

package com.test;

interface MethodRefInterface {  
       void abstractMethod();  
} 
 
public class MethodRefExample {
  
           public void method(){  
                   System.out.println("This is a method reference example");  
           }  

           public static void main(String[] args) {
                    MethodRefExample methodRef = new MethodRefExample();  
                    MethodRefInterface ref= methodRef::method;
                    ref.abstractMethod();
           }  
}  

Output:- 

This is a method reference example


2) Static method of a Class(ClassName::methodName)

MethodRefStatic.java,

package com.test;

import java.util.Arrays;
import java.util.List;

public class MethodRefStatic {
 
         public static void main(String[] args) {
                   List<Integer> list = Arrays.asList(1, 2, 3, 4);
                   System.out.println("Using lambda expression");
                   list.forEach(num -> printNumbers(num));  //using lambda expression
                   System.out.println("Using method references");
                   list.forEach(MethodRefStatic::printNumbers); //using method references
         }
 
         public static void printNumbers(int number) {
                   System.out.println("Number - " + number);
         }
}

Output:-
Using lambda expression
Number - 1
Number - 2
Number - 3
Number - 4
Using method references
Number - 1
Number - 2
Number - 3
Number - 4


3) Example of method reference to a Constructor(Class::new)

MethodRefConstruct.java,

package com.test;

interface MessageInterface{  
         MethodRefEx getMessage(String msg);  
} 

class MethodRefEx {
 
         MethodRefEx(String msg){  
                  System.out.print(msg);  
         }  
}  
class MethodRefConstruct {  
     
         public static void main(String[] args) {  
                   MessageInterface msg = MethodRefEx::new;  
                   msg.getMessage("Hello World");  
         }  
}  

Output:-
Hello World


Related Posts:--
1) Java 8 - Consumer Interface with examples
2) Java 8 forEach method with examples
3) Java 8 features with examples

No comments:

Post a Comment