Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Method References in Java 8

Overview

Method references in Java 8 provide a way to refer to methods or constructors without invoking them. They serve as a shorthand for lambda expressions that simply call an existing method. Method references can be used in conjunction with functional interfaces to make code more readable and concise.

Types of Method References

There are four kinds of method references in Java:

  • Reference to a static method: ClassName::staticMethodName
  • Reference to an instance method of a particular object: object::instanceMethodName
  • Reference to an instance method of an arbitrary object of a particular type: ClassName::instanceMethodName
  • Reference to a constructor: ClassName::new

Example 1: Reference to a Static Method

Traditional way:

List numbers = Arrays.asList(3, 2, 1);
numbers.sort((a, b) -> Integer.compare(a, b));

Using method reference:

List numbers = Arrays.asList(3, 2, 1);
numbers.sort(Integer::compare);

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

Traditional way:

Consumer printer = s -> System.out.println(s);
printer.accept("Hello, World!");

Using method reference:

Consumer printer = System.out::println;
printer.accept("Hello, World!");

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

Traditional way:

List names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));

Using method reference:

List names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println);

Example 4: Reference to a Constructor

Traditional way:

Supplier> listSupplier = () -> new ArrayList<>();

Using method reference:

Supplier> listSupplier = ArrayList::new;

Practical Use Cases

Sorting a List

List names = Arrays.asList("Charlie", "Alice", "Bob");
names.sort(String::compareTo);
System.out.println(names);

Converting a List of Strings to Uppercase

List names = Arrays.asList("Charlie", "Alice", "Bob");
List upperCaseNames = names.stream()
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());
System.out.println(upperCaseNames);

Conclusion

Method references in Java 8 enhance the readability and conciseness of code. They serve as a shorthand for lambda expressions that simply call an existing method, making the code easier to understand and maintain.