Class MethodReferenceExamples

java.lang.Object
net.jrodolfo.java_evolution.java08.MethodReferenceExamples

public class MethodReferenceExamples extends Object
Demonstrates method references, introduced in Java 8 as a compact syntax for lambdas that only call an existing method or constructor.

Lambdas made it easy to pass behavior, but many lambdas simply delegated to an existing method, such as text -> Integer.parseInt(text). That repeated information already present in the method name.

Method references solve that small readability problem. They let code say Integer::parseInt, formatter::format, String::compareToIgnoreCase, or User::new. The feature does not add new behavior beyond lambdas; it makes simple delegation easier to scan.

  • Constructor Details

    • MethodReferenceExamples

      public MethodReferenceExamples()
  • Method Details

    • parseNumbers

      public List<Integer> parseNumbers(List<String> numbers)
      Uses a static method reference.
      Parameters:
      numbers - the numeric text values to parse
      Returns:
      the parsed integer values
    • formatNames

      public List<String> formatNames(List<String> names)
      Uses a bound instance method reference, where the receiver object already exists.
      Parameters:
      names - the names to format
      Returns:
      formatted names produced by the same formatter instance
    • sortIgnoringCase

      public List<String> sortIgnoringCase(List<String> names)
      Uses an unbound instance method reference, where the receiver is supplied by each stream element.
      Parameters:
      names - the names to sort
      Returns:
      a new list sorted without considering letter case
    • createUsers

      public List<MethodReferenceExamples.User> createUsers(List<String> names)
      Uses a constructor reference to create a domain object from each input value.
      Parameters:
      names - the names used to create users
      Returns:
      users created with User::new
    • createUserWithFunction

      public MethodReferenceExamples.User createUserWithFunction(String name)
      Shows that constructor references can also be assigned to functional interfaces.
      Parameters:
      name - the user's name
      Returns:
      a user created by a Function
    • createFormatterWithSupplier

      public MethodReferenceExamples.NameFormatter createFormatterWithSupplier()
      Shows a zero-argument constructor reference with Supplier.
      Returns:
      a formatter created by calling NameFormatter::new