Wednesday, 13 June 2018

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. s-> System.out.println(s));

but here you can replace lambda expression with method reference to improve readability as shown below: 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 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 which takes a value and prints in the console than instead of passing lambda expression, just pass the println() method of PrintStream class which you can access as System.out::println.

Remeber there is no parenthesis when you refer a method using method reference or lambda expression in Java 8.  If you want to learn more, The Complete Java MasterClass is a good place to start with.

Real world Example of Double Colon Operator in Java 8

Here is a real-world example fo method reference using 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 double colon operator or method reference.

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

Oracle Java Tutorial and Material, Oracle Java Certifications, Oracle Java 8

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 double colon operator. 

Oracle Java Tutorial and Material, Oracle Java Certifications, Oracle Java 8

That's all about double colon operator of Java 8. As I said, it's known as method reference and can be used to refer 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 more cleaner code.

Related Posts