Saturday, March 21, 2020

What is double colon (::) operator in Java 8 - Example

The double colon (::) operator is known as the method reference in Java 8. Method references are expressions which have the same treatment as a lambda expression, but instead of providing a lambda body, they refer to an existing method by name. For example, to print all elements of the list, you can use the forEach() method as follows

list.stream.forEach( s-> System.out.println(s));

but here you can replace lambda expression with method reference to improve readability as shown below:

list.stream.forEach( System.out::println);

For referring a static method, you can either use className or instanceRef, but to refer an instance method of a particular object, you need instanceRef.

Here are some examples of a method reference in Java 8:

1. A static method (ClassName::methodName) like Person::getAge

2. An instance method of a particular object (instanceRef::methodName) like System.out::println

3. A super method of a particular object (super::methodName)

4. An instance method of an arbitrary object of a particular type (ClassName::methodName)

5. A class constructor reference (ClassName::new) like ArrayList::new

6. An array constructor reference (TypeName[]::new) like String[]:new

The idea is that if you are passing a lambda expression, e.g. a function that takes a value and prints in the console than instead of giving lambda expression, just pass the println() method of PrintStream class which you can access as System.out::println.

Real-world Example of Double Colon Operator in Java 8


Here is a real-world example fo method reference using a double colon operator in Java 8. In this example, we are creating a Comparator which compares person by their age. In the first example, we have used a lambda expression to pass the logic to compare age, while in the second line of code, we have used a double colon operator or method reference.

You can see that the second example is much more readable and clean:

Oracle Java Cert Exam, Oracle Java Learning, Oracle Java Guides, Oracle Java Learning

Btw, If you are using IDE like Eclipse, NetBeans, or IntelliJ IDEA, the IDE will also suggest you convert your lambda expression to method reference as shown in the following screenshot.

This confirms that it's a best practice in Java 8 to convert lambda expression to a method reference or constructor reference using a double colon operator.

Oracle Java Cert Exam, Oracle Java Learning, Oracle Java Guides, Oracle Java Learning

That's all about the double colon operator of Java 8. As I said, it's known as method reference and can be used to refer to an existing method by name instead of using a lambda expression.  It's a  Java 8 best practice to favor method reference over lambda expression as it results in cleaner code.

Related Posts

0 comments:

Post a Comment