Java8 - Method references

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:28:00 Viewed : 234


Method references in Java provide a concise way to express lambda expressions when the lambda body simply calls an existing method. They enable you to refer to a method without having to define a corresponding lambda expression. Method references are often more readable and expressive than equivalent lambda expressions, especially when working with existing methods or constructors.

There are four types of method references in Java:

  1. Reference to a Static Method:

    • Syntax: ClassName::staticMethodName
    • Example:
      java
      // Lambda expression Function<String, Integer> lengthFunction = s -> s.length(); // Method reference Function<String, Integer> lengthFunctionReference = String::length;
  2. Reference to an Instance Method of a Particular Object:

    • Syntax: instance::instanceMethodName
    • Example:
      java
      // Lambda expression String prefix = "Hello, "; Function<String, String> greetFunction = s -> prefix.concat(s); // Method reference String prefixReference = "Hello, "; Function<String, String> greetFunctionReference = prefixReference::concat;
  3. Reference to an Instance Method of an Arbitrary Object of a Particular Type:

    • Syntax: ClassName::instanceMethodName
    • Example:
      java
      // Lambda expression Comparator<String> lengthComparator = (s1, s2) -> Integer.compare(s1.length(), s2.length()); // Method reference Comparator<String> lengthComparatorReference = Comparator.comparing(String::length);
  4. Reference to a Constructor:

    • Syntax: ClassName::new
    • Example:
      java
      // Lambda expression Supplier<List<String>> listSupplier = () -> new ArrayList<>(); // Method reference Supplier<List<String>> listSupplierReference = ArrayList::new;

Method references are especially useful when working with the Stream API, making code more concise and readable. Here is an example using a method reference with the Stream API:

java
List<String> words = Arrays.asList("apple", "banana", "orange"); // Lambda expression words.stream().map(s -> s.toUpperCase()).forEach(System.out::println); // Method reference words.stream().map(String::toUpperCase).forEach(System.out::println);

In the above example, String::toUpperCase is a method reference, which is a more concise way to express the transformation of each element in the stream to its uppercase form.

Search
Related Articles

Leave a Comment: