Method Reference using the Double Colon(::) Operator3 min read

Java

Overview

Double Colon(::) Operator is actually known as Method Reference in Java 8. They can mostly be used in places where we can use Lambda, but not always.
The noticeable advantages of Method Reference is that it makes the code more concise, readable and easy to follow.

Notation as mentioned in the title:

className::methodName

How It Works?

When we use double colon operator, there is no need to pass the parameters of the calling method because the parameters are implicitly passed to the method from the context where the double colon operator is used.
For example, if a forEach is called on a list, then whilst iterating on the objects, the current object in context would be passed to the referenced method.

Types of Method Reference

Type Syntax Method Reference Lambda expression
Reference to a static method ClassName::staticMethodName String::valueOf  s -> String.valueOf(s)
Reference to an instance method
of a particular object
instance::instanceMethodName s:toString  () -> “string”.toString()
Reference to an instance method
of an arbitrary object of a particular type
ClassName:instanceMethodName String::toString  s -> s.toString()
Reference to a constructor ClassName::new String::new  () -> new String()

1. Reference to a Static Method

public class Static_Reference {
    public static void main(String[] args) {

        List listOfNames = Arrays.asList("name1", "name2");
        // Method Reference
        listOfNames.forEach(Static_Reference::printNames);
        // Lambda Expression
        listOfNames.forEach(names -> printNames(names));
    }

    public static void printNames(String name) {
        System.out.print(name +" ");
    }
}
output:name1 name2

Using Arrays.asList(), we have first defined an ArrayList followed by a call to forEach on the listOfNames. Inside the forEach, as per syntax className::staticMethodName we have called the printNames static method of class Static_Reference.

2. Reference to an Instance Method of a Particular Object

public class Method_Reference {
	public static void main(String args[]) {
		final List list = Arrays.asList("c", "b", "c", "a");

		Method_Reference comparator = new Method_Reference();
		// Method Reference to an Instance method
		Collections.sort(list, comparator::compare);
		// Lambda expression
		Collections.sort(list, (a, b) -> comparator.compare(a, b));
	}

	public int compare(final String a, final String b) {
		return a.compareTo(b);
	}

To understand Instance method reference, first, we define an Instance method compare(), then next inside the Collections sort() method, we reference it using the class reference(comparator) followed by the instance method with the double colon operator in between.

3. Reference to an Instance Method of an Arbitrary Object of a Particular Type

public class ArbitraryType {
    public static void main(String[] args) {
        List li = Arrays.asList(
            new Employee("emp1"), new Employee("emp2"));

        li.forEach(Employee::printEmpName);
    }
}
class Employee {
    private String empName;

    public Employee(String empName) {
        this.empName = empName;
    }
    public void printEmpName() {
        System.out.print(empName + " ");
    }
}
output:emp1 emp2

In the Example above, class Employee is the Particular type and its objects that are looped inside the forEach are the arbitrary objects. Inside the forEach, all the defined objects are one by one calling the instance method printEmpName() that prints the empName of the current object in context.

4. Reference to a Constructor

@functionalInterface
interface Factory{
    public String demo(String original);
}
public static void main(String[] args) {
     Factory fc = String::new;
     System.out.println(fc.demo("Hello"));
}
output:Hello

To reference a constructor using double colon operator, first, we define a functional interface named ‘Factory’ with one method named demo() and whose definition resembles with that of a String class constructor.

Next, using demo() method signature, we can call the String class constructor that takes in String as an input parameter, after applying double colon operator it will look like the highlighted code.

Finally, to print any String e.g. “Hello”, we can simply call the demo method, whose implementation would be the String constructor we invoked in the previous step.

Conclusion

In this article, we learned how Method Referencing in Java 8 works, plus all the four types of Method Referencing along with examples and description.

As usual, you can find the code on Github

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.