Java8 - When and how to use method references

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 05:26:16 Viewed : 245


Method references in Java provide a concise syntax for creating lambda expressions that directly invoke methods or constructors. Knowing when and how to use method references can lead to cleaner and more readable code. Here are some guidelines on when and how to use method references:

When to Use Method References:

  1. Existing Methods:

    • Use method references when invoking an existing method, especially when the lambda expression merely calls an existing method.
    java
    List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Lambda expression names.forEach(name -> System.out.println(name)); // Method reference names.forEach(System.out::println);
  2. Instance Methods on Particular Instances:

    • Use method references when invoking an instance method on a particular instance.
    java
    String sampleString = "Hello, World!"; // Lambda expression Predicate<String> isEmptyLambda = (str) -> str.isEmpty(); // Method reference Predicate<String> isEmptyReference = sampleString::isEmpty;
  3. Instance Methods on Arbitrary Instances:

    • Use method references when invoking an instance method on the first parameter as an input.
    java
    // Lambda expression BiFunction<String, String, Boolean> startsWithLambda = (str, prefix) -> str.startsWith(prefix); // Method reference BiFunction<String, String, Boolean> startsWithReference = String::startsWith;
  4. Constructors:

    • Use constructor references when creating new instances of a class.
    java
    // Lambda expression Supplier<List<String>> listSupplierLambda = () -> new ArrayList<>(); // Constructor reference Supplier<List<String>> listSupplierReference = ArrayList::new;
  5. Functional Interfaces:

    • Use method references when working with functional interfaces and the method signature matches.
    java
    // Lambda expression Function<Integer, String> toStringLambda = (num) -> String.valueOf(num); // Method reference Function<Integer, String> toStringReference = String::valueOf;

How to Use Method References:

  1. Static Method References:

    • Syntax: ClassName::staticMethodName
    java
    Function<Integer, String> staticMethodRef = String::valueOf;
  2. Instance Method References on a Particular Instance:

    • Syntax: instance::instanceMethodName
    java
    Predicate<String> instanceMethodRef1 = "Hello"::equals;
  3. Instance Method References on an Arbitrary Instance:

    • Syntax: ClassName::instanceMethodName
    java
    BiFunction<String, String, Boolean> arbitraryInstanceMethodRef = String::endsWith;
  4. Constructor References:

    • Syntax:
      • For parameterless constructors: ClassName::new
      • For constructors with parameters: ClassName::new
    java
    Supplier<List<String>> constructorRef = ArrayList::new;
  5. Reference to an Instance Method of an Arbitrary Object of a Particular Type:

    • Syntax: ClassName::instanceMethodName
    java
    BiFunction<String, String, Boolean> arbitraryInstanceMethodRef = String::startsWith;

Guidelines:

  • Readability:

    • Use method references when they enhance code readability. They are particularly useful for concise expressions that directly map to method invocations.
  • Existing Methods:

    • Prefer method references when the lambda expression is essentially a call to an existing method, especially when the method name and parameters match.
  • Functional Interfaces:

    • Use method references with functional interfaces when the method signature matches. This can make the code more expressive and less verbose.
  • Constructor References:

    • Use constructor references when creating new instances of a class. This can be more concise than using lambda expressions.
  • Instance Methods on Particular Instances:

    • Use method references when invoking instance methods on particular instances, especially when the instance is already available.
  • Instance Methods on Arbitrary Instances:

    • Use method references when invoking instance methods on the first parameter as an input, especially when the instance is part of the method signature.

Example:

java
import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; public class MethodReferencesExample { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Method reference for static method names.forEach(System.out::println); // Method reference for instance method on a particular instance Predicate<String> isEmptyReference = "Hello"::equals; // Method reference for instance method on an arbitrary instance Function<String, Boolean> startsWithReference = String::startsWith; // Constructor reference Supplier<List<String>> listSupplierReference = ArrayList::new; // Functional interface with method reference Function<Integer, String> toStringReference = String::valueOf; } }

In this example, various types of method references are used to demonstrate when and how to apply them. The code focuses on readability and concise expression of method invocations.

Search
Related Articles

Leave a Comment: