Method Reference(::) Java 8
copy from: https://javatechonline.com/method-reference-java-8/
Method Reference is a wonderful feature introduced in Java 8. Apart from taking advantage of functional programming, one of the biggest advantages in using a Lambda expression is to minimize the lines of code. Similarly, Method Reference(::) Java 8 also minimizes lines of code even more than Lambda. However, we use both of them in the presence of functional interfaces only. Moreover, It is also a concise and simpler form of lambda expression. In this article, we will also learn how to change a Lambda expression into a method reference. Let’s start discussing about ‘Method Reference(::) Java 8’ and it’s related concepts.
What is Method Reference(::)?
As we have seen in Lambda expression topic that we use lambda expressions to implement Functional interfaces with minimum lines of code and even to get better code readability. Similarly, we can use Method Reference(::) Java 8 to implement Functional interfaces with even lesser code again than lambda expressions and this time we get the benefit of code re-usability as well, because we don’t provide an implementation for functional interface. Instead, we provide reference to already existing method (with similar argument types) to simplify the implementation of the functional interface using a double colon (::) operator. This process of providing reference to pre-existing method is called Method reference.
From the above definition it is clear that while applying Method References our focus is always on the pre-existing methods which are well suited to the implementation of Functional Interface. In fact, pre-existing methods should have same arguments in number & type and there are no restrictions on their return type as such. Of course, here one thing is equally important to keep in mind that Method references & Lambda expressions both can only be used in context of Functional Interfaces.
interface A {
public void getName(String name);
}
public class Test {
public static void getInfo(String info) {
System.out.println(info);
}
public static void main(String[] args) {
A a = (String s) -> System.out.println(s); //providing implementation of getName(String name) using Lambda Expression
a.getName("SAM is executing");
// pay attention on below code, getInfo is a normal method, but it can also be used like this,
// also static is necessary if using className::method, instead we can use instanceName::method without static keyword
A a1 = Test::getInfo; // refering to pre-existing getInfo(String info) of class Test as arguments are same as getName(String name)
a1.getName("getInfo() of Test class is executing");
}
}
In the above code snippet, Interface A, is a functional interface. The Single abstract method(SAM), getName(String name) of interface A has the same argument in number & type as the pre-existing method getInfo(String info) of class Test. Therefore, we can refer getInfo(String info) as an implementation of Functional interface A without any problem. Hence, the syntax for Method reference will be ClassName::methodName if it is static method.
Syntax to write Method References
Before knowing how to write them, let’s first categorize the Method Reference(::) Java 8. Here, syntax to write Method Reference(::) Java 8 is different in different cases. In general, we can provide Method references in three ways, sometimes called the types of it.
- Static Method References
- Instance method/non-static Method References
- Constructor References
Now, let’s try to observe them one by one from below table.
Note : In addition, we have two more besides above three:
- Method References of an arbitrary object of a given type
- Method References from a super class method. We will cover them separately in below sections.
Examples of each Type of Method Reference(::) Java 8
Method reference to a static method of a class :
interface A { public boolean checkSingleDigit(int x); } class Digit { public static boolean isSingleDigit(int x) { return x > -10 && x < 10; } } public class TestStaticMethodReference { public static void main(String[] args) { //*** Using Lambda Expression ***// A a1 = (x) -> { return x > -10 && x < 10;}; System.out.println(a1.checkSingleDigit(10)); //*** Using Method Reference ***// A a2 = Digit::isSingleDigit; System.out.println(a2.checkSingleDigit(9)); } }
In the above example, we have functional Interface A. We have implemented the single abstract method checkSingleDigit(int x) using Lambda expression in highlighted line. But while using Method reference, we have just referred the similar already existing static method isSingleDigit(int x) of class Digit.
Method reference to an Instance method of a class :
interface B { public void add(int x, int y); } class Addition { public void sum(int a, int b) { System.out.println("The sum is :"+(a+b)); } } public class TestInstanceMethodReference { public static void main(String[] args) { Addition addition = new Addition(); //*** Using Lambda Expression ***// B b1 = (a,b) -> System.out.println("The sum is :"+(a+b)); b1.add(10, 14); //*** Using Method Reference ***// B b2 = addition::sum; b2.add(100, 140); } }
In the above example, we have functional Interface B. We have implemented the single abstract method add(int x, int y) using Lambda expression in highlighted line. While using Method reference, we have just referred the similar already existing method sum(int a, int b) of class Addition but after creating an object of the class this time.
Constructor Reference
When single abstract method’s return type is any Object, we will go with the constructor reference.
interface C { public Employee getEmployee(); } interface D { public Employee getEmployee(String name, int age); } class Employee { String eName; int eAge; public Employee(){} public Employee(String eName, int eAge) { this.eName = eName; this.eAge = eAge; } public void getInfo() { System.out.println("I am a method of class Employee"); } } public class TestConstructorReference { public static void main(String[] args) { //*** Using Lambda Expression ***// C c1 = () -> new Employee(); c1.getEmployee().getInfo(); D d1 = (name,age) -> new Employee(name,age); d1.getEmployee("Tony", 34).getInfo(); //*** Using Method Reference ***// C c2 = Employee::new; c2.getEmployee().getInfo(); D d2 = Employee::new; d2.getEmployee("Tony", 34).getInfo(); } }
In the above code snippet, we have two Functional interfaces C & D. Interface C has abstract method with no arguments whereas D has with arguments. We will have same constructor reference code in both cases as shown in the highlighted lines of code. Also, if you run the code in your development environment, you will get the same output in each case.
Example of Reference to an Instance Method of an Arbitrary Object of a Particular Type
public class TestArbitraryObjectMethodReference { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(15, 33, 59, 24, 40, 2, 19, 25,60); //*** Using Anonymous Inner class ***// Collections.sort(numbers, new Comparator<Integer>() { public int compare(Integer i1,Integer i2) { return i1.compareTo(i2); } }); System.out.println("************* Using Anonymous Inner class ***************"); numbers.forEach(System.out::println); //*** Using Lambda Expression ***// System.out.println("************* Using Lambda Expression *******************"); Collections.sort(numbers,(i1,i2) ->i1.compareTo(i2)); numbers.forEach(System.out::println); //*** Using Method Reference ***// System.out.println("************* Using Method reference ********************"); Collections.sort(numbers,(Integer::compareTo)); numbers.forEach(System.out::println); } }
In the above code snippet we have shown the three ways to implement a Functional Interface (Comparator) simultaneously. Of course, All of them outputs the same result.
Difference between reference to an Instance method of a particular object & an arbitrary Object of a given type
You might have some doubt on difference between both references, so now it’s right time to talk about them. To illustrate, let’s observe the examples given in the table below. I am sure you will get the clear idea on differences. There is no need to explain more about this.
Method reference Examples of Particular Object Vs an Arbitrary Object
Reference to super class & child class method using super & this keyword
Now we will see the use of super & this keyword in writing Method references accordingly.
interface A { public void sayHello(); } class SuperClass { public void superHello(){ System.out.println("I am inside SuperTest class"); } } class ChildClass extends SuperClass{ public void childHello() { System.out.println("I am inside SubTest class"); } public void testHello() { //***Using Method reference :super class method***// A a1= super::superHello; a1.sayHello(); //***Using Lambda Expression :super class method***// A a3= () -> System.out.println("I am inside SuperTest class"); a3.sayHello(); //***Using Method reference :current class method***// A a2= this::childHello; a2.sayHello(); //***Using Lambda Expression :current class method***// A a4= () -> System.out.println("I am inside SubTest class"); a4.sayHello(); } } public class Test { public static void main(String[] args) { ChildClass t = new ChildClass(); t.testHello(); } }
As in the above code snippet, we have a functional interface ‘A‘ with Single Abstract method sayHello(). We have two classes SuperClass & ChildClass. Existing methods superHello() & childHello() are referred to write method references using super & this keyword respectively.
Furthermore, If you want to learn more about Method Reference(::) Java 8, kindly visit official Oracle Documentation.
FAQs
What is the method reference in Java 8?
Method Reference is a new feature of Java 8. Using Method Reference, we provide a reference to already existing method (with similar argument types) to facilitate the implementation of a functional interface using a double colon (::) operator. This process of providing reference to pre-existing method is called Method reference. Moreover, Method Reference helps us to make shorter code as compared to a lambda expression.
What is the benefit of using method reference in Java 8?
What is difference between lambda expression and method reference?
Using Lambda Expression, we provide the implementation of a functional interface. In Method Reference, instead of providing an implementation of a functional interface’s method, we provide a reference to the pre-existing method using the double colon (::) operator.
What are three ways for method reference?
Below are the three ways for method reference:
- Reference to a static method of a class
- Reference to an Instance method of a class
- Constructor Reference
Why do we need method references in Java?
As aforementioned, method references make the code, simpler, shorter, and more readable by just referencing the pre-existing methods rather than providing a custom implementation.
Are method references faster?
Method Reference & Lambda has approximately similar performance. When we use lambda with Java 8 Streams, it provides better performance than the method reference.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律