Java

Method References – Java 8

Lambda expressions in Java 8 were covered in the prior lesson. Here, we’ll talk about method references, another new feature of Java 8. A method reference is a simplified way to invoke a method using a lambda expression. For instance:
If your lambda expression like the following:

str -> System.out.println(str)

then a method reference like this may be used in its place:

System.out::println

The class or object is separated from the method name by the:: operator in method references (we will learn this with the help of examples)

Four types of method references

  1. Method references to instance methods of objects: object::instanceMethod
  2. Method references to static methods of classes: Class::staticMethod
  3. Method references to instance methods of any kind of arbitrary object: Class::instanceMethod
  4. Method references to constructors: Class::new

1. Method reference to an instance method of an object

@FunctionalInterface 
interface MyInterface{  
    void display();  
}  
public class Example {  
    public void myMethod(){  
	System.out.println("Instance Method");  
    }  
    public static void main(String[] args) {  
	Example obj = new Example();   
	// Method reference using the object of the class
	MyInterface ref = obj::myMethod;  
	// Calling the method of functional interface  
	ref.display();  
    }  
}

Output:

Instance Method

2. Method reference to a static method of a class

import java.util.function.BiFunction;  
class Multiplication{  
   public static int multiply(int a, int b){  
	return a*b;  
   }  
}  
public class Example {  
   public static void main(String[] args) {  
	BiFunction<Integer, Integer, Integer> product = Multiplication::multiply;  
	int pr = product.apply(11, 5);  
	System.out.println("Product of given number is: "+pr);  
   }  
}

Output:

Product of given number is: 55

3. Method reference to an instance method of an arbitrary object of a particular type

import java.util.Arrays;
public class Example {  

   public static void main(String[] args) {  
	String[] stringArray = { "Steve", "Rick", "Aditya", "Negan", "Lucy", "Sansa", "Jon"};
	/* Method reference to an instance method of an arbitrary 
	 * object of a particular type
	 */
	Arrays.sort(stringArray, String::compareToIgnoreCase);
	for(String str: stringArray){
		System.out.println(str);
	}
   }  
}

Output:

Aditya
Jon
Lucy
Negan
Rick
Sansa
Steve

4. Method reference to a constructor

@FunctionalInterface 
interface MyInterface{  
    Hello display(String say);  
}  
class Hello{  
    public Hello(String say){  
        System.out.print(say);  
    }  
}  
public class Example {  
    public static void main(String[] args) { 
    	//Method reference to a constructor
        MyInterface ref = Hello::new;  
        ref.display("Hello World!");  
    }  
}

Output:

Hello World!

Related Articles

Leave a Reply

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

Back to top button