In the previous post, we learned about the Java 8
Consumer interface with examples. In this post, we will discuss another important feature introduced in Java 8: method references.A method reference is a shorthand syntax for a lambda expression that invokes an existing method. In earlier versions of Java, we invoked a method using the dot (.) operator on an object. In Java 8, the :: operator can be used to refer to a method directly, making the code more concise and readable.
The following 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