0Pricing
Java Academy · Lesson

Arbitrary-Instance Method References

Reference an instance method without specifying the receiver — used heavily with Stream operations.

What Are Arbitrary-Instance References?

An arbitrary-instance method reference uses ClassName::instanceMethod. Here the first argument of the functional interface serves as the receiver — each element becomes the object on which the method is called.

import java.util.*;
import java.util.stream.*;

List<String> names = List.of("alice","bob","carol");

// String::toUpperCase — receiver is each list element
List<String> upper = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());
System.out.println(upper); // [ALICE, BOB, CAROL]

How the Receiver Is Resolved

For an arbitrary-instance reference Type::method, the functional interface's first parameter becomes this (the receiver):

// String::length matches Function<String, Integer>
// Equivalent to: s -> s.length()
Function<String, Integer> len = String::length;
System.out.println(len.apply("Java")); // 4

// String::isEmpty matches Predicate<String>
// Equivalent to: s -> s.isEmpty()
Predicate<String> isEmpty = String::isEmpty;
System.out.println(isEmpty.test(""));   // true

All lessons in this course

  1. Static Method References
  2. Instance Method References on a Specific Instance
  3. Arbitrary-Instance Method References
  4. Constructor References
← Back to Java Academy