Method References In java

Reading Time: 3 minutes

One of the most welcome changes in Java 8 was the introduction of lambda expression. These allow us to forego anonymous classes, greatly reducing boilerplate code and improving readability.

let’s take out the nectar from this ocean of method references.

Method References

These are a special type of lambda expressions. They allow us to pass the name of a method where a Functional interface is expected and often used to create simple lambda expressions by referencing existing methods. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same. In general, one doesn’t have to pass arguments to method references.

Types of Method References

There are four kinds of method references:

  • Static methods
  • Instance methods of particular objects
  • Instance methods of an arbitrary object of a particular type
  • Constructor

1.Reference to a Static Methods

You can refer to static method defined in the class. Following is the syntax and example which describe the process of referring static method in Java.

Syntax

ContainingClass::staticMethodName  

Example

interface Speakable{
void speak();
}
public class MethodReference {
public static void speakSomething(){
System.out.println(” Inside static.”);
}
public static void main(String[] args) {
Sayable sayable = MethodReference::speakSomething;
sayable.speak();
}
}

Output

Inside static.

2. Reference to an Instance Method of a Particular Object

In this section we are going to demonstrate instance method of a particular Object, let’s consider two classes:

public class Bicycle {

    private String brand;
    private Integer frameSize;
}

public class BicycleComparator implements Comparator {
    @Override
    public int compare(Bicycle a, Bicycle b) {
        return a.getFrameSize().compareTo(b.getFrameSize());
    }
}

let’s create a BicycleComparator object to compare bicycle frame sizes:

BicycleComparator bikeFrameSizeComparator = new BicycleComparator();

Here, we could use a lambda expression to sort bicycles by frame size, but we had need to specify two bikes for comparison, and can be understand in below example:

createBicyclesList().stream()
 .sorted((a, b) -> bikeFrameSizeComparator.compare(a, b));

Instead of this, we can use here a reference to have the compiler handle parameter passing for us,like

createBicyclesList().stream()
 .sorted(bikeFrameSizeComparator::compare);

Hence, the method reference is much cleaner and more readable and as our intention is clearly shown by the code.

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

This type of reference is similar to the previous example, but without having to create a custom object to perform the comparison. Let’s create an Integer list that we want to sort:

List<Integer> numbers = Arrays.asList(5, 13, 27, 14, 34, 1, 19, 8);

If we use a classic lambda expression, both parameters need to be passed explicitly, whereas using a this type reference is much simpler:

numbers.stream()
  .sorted((a, b) -> a.compareTo(b));
numbers.stream()
  .sorted(Integer::compareTo);

Even though it’s still a one-liner, the method reference is much easier to read and understand.

4.Reference to a Constructor

You can refer a constructor by using the new keyword. Here, we are referring constructor with the help of functional interface.

Syntax

ClassName::new

Example

interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage(“Hello”);
}
}

Output

Hello

Conclusion

In this, we learned what method references are in Java and how to use them to replace lambda expressions, thereby improving readability. If a lambda expression only calls an existing method then using method reference can make code more readable and clear.

knoldus

Written by 

With the ability to learn new things, I am a software intern at Knoldus Inc. I enjoy whenever I solve problems and code them in a good way.