Java 8 Method Reference Examples

In Java 8, method references provide a concise way to refer to methods or constructors using a special syntax. They can be used in place of lambda expressions when the lambda expression simply calls an existing method. In this post, we are going to see Java 8 method reference examples.

Note – The main benefit of method reference is code reusability.

Method references make our code more readable and maintainable by reducing lambda expressions. There are four types of method references in Java 8:

  1. Reference to a Static Method: We can reference a static method of a class using the syntax ClassName::staticMethodName. Here’s an example:
// Lambda expression
Function<String, Integer> parseInt = (str) -> Integer.parseInt(str);

// Method reference
Function<String, Integer> parseIntRef = Integer::parseInt;

int result = parseIntRef.apply("123"); // Parses "123" and returns 123
  1. Reference to an Instance Method of a Particular Object: We can reference an instance method of a specific object using the syntax object::instanceMethodName. Here’s an example:
List<String> strings = Arrays.asList("apple", "banana", "cherry");

// Lambda expression
strings.forEach((str) -> System.out.println(str));

// Method reference
strings.forEach(System.out::println);
  1. Reference to an Instance Method of an Arbitrary Object of a Particular Type: We can reference an instance method of an arbitrary object of a particular type using the syntax ClassName::instanceMethodName. Here’s an example:
List<String> strings = Arrays.asList("apple", "banana", "cherry");

// Lambda expression
strings.forEach((str) -> System.out.println(str.length()));

// Method reference
strings.forEach(String::length);
  1. Reference to a Constructor: We can reference a constructor using the syntax ClassName::new. Here’s an example:
// Lambda expression
Supplier<List<String>> listSupplier = () -> new ArrayList<>();

// Method reference
Supplier<List<String>> listSupplierRef = ArrayList::new;

List<String> list = listSupplierRef.get(); // Creates a new ArrayList

Let’s see a few more Java 8 method reference examples.

Example 1: Reference to a Static Method

import java.util.function.Function;

public class StaticMethodReferenceExample {
    public static void main(String[] args) {
        // Using a lambda expression
        Function<String, Integer> parseInt = (str) -> Integer.parseInt(str);

        // Using a method reference
        Function<String, Integer> parseIntRef = Integer::parseInt;

        int result = parseIntRef.apply("123"); // Parses "123" and returns 123
        System.out.println("Result: " + result);
    }
}

Output:

Result: 123

In this example, we have a lambda expression parseInt that takes a String and parses it into an Integer using Integer.parseInt. The method reference parseIntRef simplifies this by directly referencing the static method Integer.parseInt. The output, in both cases, is 123.

Example 2: Reference to an Instance Method of a Particular Object

import java.util.Arrays;
import java.util.List;

public class InstanceMethodReferenceExample {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("apple", "banana", "cherry");

        // Using a lambda expression
        strings.forEach((str) -> System.out.println(str));

        // Using a method reference
        strings.forEach(System.out::println);
    }
}

Output:

apple
banana
cherry
apple
banana
cherry

In this example, we have a list of strings, and we want to print each string. The lambda expression in Example 1 uses a lambda to call System.out.println(str). Example 2 simplifies this by directly referencing the println method of System.out

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

import java.util.Arrays;
import java.util.List;

public class ArbitraryObjectMethodReferenceExample {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("apple", "banana", "cherry");

        // Using a lambda expression
        strings.forEach((str) -> System.out.println(str.length()));

        // Using a method reference
        strings.forEach(String::length);
    }
}

Output:

5
6
6
5
6
6

In this example, we have a list of strings, and we want to get the length of each string. The lambda expression in Example 1 uses a lambda to call str.length(). Example 2 simplifies this by directly referencing the length method of the String class.

Example 4: Reference to a Constructor

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class ConstructorReferenceExample {
    public static void main(String[] args) {
        // Using a lambda expression
        Supplier<List<String>> listSupplier = () -> new ArrayList<>();

        // Using a method reference
        Supplier<List<String>> listSupplierRef = ArrayList::new;

        List<String> list = listSupplierRef.get(); // Creates a new ArrayList
        System.out.println("List size: " + list.size());
    }
}

Output:

List size: 0

In this example, we want to create a new ArrayList. The lambda expression in Example 1 uses a lambda to create a new ArrayList instance. Example 2 simplifies this by directly referencing the constructor of the ArrayList class using ArrayList::new.

Example 5: Reference to an Instance Method of an Object from a Particular Type

import java.util.Arrays;
import java.util.List;

public class InstanceMethodOfObjectReferenceExample {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("apple", "banana", "cherry");

        // Using a lambda expression
        strings.sort((s1, s2) -> s1.compareTo(s2));

        // Using a method reference
        strings.sort(String::compareTo);

        System.out.println(strings);
    }
}

Output:

[apple, banana, cherry]

In this example, we have a list of strings, and we want to sort them in lexicographical order. Example 1 uses a lambda expression with the compareTo method to achieve this. Example 2 simplifies it by directly referencing the compareTo method of the String class to perform the comparison during sorting.

These complete examples include the main method and demonstrate different types of method references with their respective outputs.

Method references can make your code more concise and expressive, especially when you’re working with functional interfaces like Consumer, Function, and Predicate. They are a powerful feature introduced in Java 8 to improve the readability and maintainability of your code when working with lambda expressions.

That’s all about Java 8 Method Reference Examples.

See Java 8 method reference docs.

Other Java 8 tutorials.