Java Method References

Introduction

Java Method References is a feature introduced in Java 8 that allows us to refer to a method or constructor of a class without actually invoking it. This feature simplifies the code and makes it more readable.

In Java, we can use lambda expressions to create functional interfaces. A functional interface is an interface that has only one abstract method. Method references provide another way to create instances of functional interfaces.

Java Method References Types

There are four types of method references in Java:

  1. Reference to a static method
  2. Reference to an instance method of an object
  3. Reference to an instance method of a particular object
  4. Reference to a constructor

Let’s take a look at each type of method reference with an example.

Reference to a static method

Function<Integer, Integer> square = MyClass::square;
int result = square.apply(5); // returns 25

In this example, we have a class MyClass that has a static method square which takes an integer and returns its square. We create a Function that takes an integer and returns an integer. We use a method reference MyClass::square to create an instance of this Function.

Reference to an instance method of an object

List<String> names = Arrays.asList("John", "Mary", "Alex");
names.forEach(System.out::println);

In this example, we have a list of names. We use the forEach method to print each name in the list. We use a method reference System.out::println to refer to the instance method println of the System.out object.

Reference to an instance method of a particular object

String str = "Hello, World!";
Function<Integer, Character> charAt = str::charAt;
char result = charAt.apply(7); // returns 'W'

In this example, we have a string str. We create a Function that takes an integer and returns a character. We use a method reference str::charAt to create an instance of this Function.

Reference to a constructor

Supplier<List<String>> listSupplier = ArrayList::new;
List<String> names = listSupplier.get();

In this example, we have a Supplier that creates a new ArrayList. We use a constructor reference ArrayList::new to create an instance of this Supplier.

Java Method References to reference user-defined methods

In addition to referencing built-in methods, Java Method References also allow us to reference user-defined methods. This can be useful in situations where we want to pass a method reference as a parameter to a higher-order function or to create an instance of a functional interface.

To reference a user-defined method, we need to have a functional interface that matches the signature of the method. For example, let’s say we have a method isEven in a utility class that takes an integer and returns a boolean value indicating whether the integer is even or not:

public class Utils {
    public static boolean isEven(int n) {
        return n % 2 == 0;
    }
}

We can define a functional interface that takes an integer and returns a boolean value, like this:

@FunctionalInterface
interface IntPredicate {
    boolean test(int n);
}

We can now reference the isEven method using a method reference like this:

IntPredicate evenPredicate = Utils::isEven;

We can then use the evenPredicate instance to test whether a given integer is even or not, like this:

System.out.println(evenPredicate.test(10)); // prints "true"
System.out.println(evenPredicate.test(7)); // prints "false"

Another example of referencing a user-defined method is when working with collections. Let’s say we have a list of integers and we want to filter out the even numbers. We can use the filter method of the Stream class and pass a method reference to the isEven method as the filtering criteria:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
                                    .filter(Utils::isEven)
                                    .collect(Collectors.toList());
System.out.println(evenNumbers); // prints "[2, 4, 6, 8, 10]"

In this example, we create a stream from the numbers list, and then use the filter method to create a new stream that only contains the even numbers. We pass the isEven method reference to the filter method as the filtering criteria.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author