Instance Method References on Arbitrary Objects
You'll learn how to use method references where the first argument becomes the object calling the method—perfect for operations on collections of objects.
Understanding the Pattern
You've already seen instance method references on specific objects (object::method). Now we look at a more powerful variant: ClassName::instanceMethod.
This syntax looks like a static method reference, but it's quite different. When you write String::toUpperCase, you're not calling a static method—you're creating a reference to the instance method toUpperCase(). The trick is that the first parameter of your functional interface becomes the target object.
How It Works
Think of it like this: when you write (String s) -> s.toUpperCase(), Java sees that s is both:
- The first parameter coming in
- The object you're calling the method on
You can abbreviate this pattern as String::toUpperCase. Java automatically routes the first parameter to become the object that executes the instance method.
Common Example
List<String> words = Arrays.asList("hello", "world", "java");
words.forEach(String::toUpperCase); // Won't work as-is in forEach
Better with map operations (once you learn streams):
// Conceptually: each String s becomes s.toUpperCase()
BiPredicate<String, String> startsWithChecker = String::startsWith;
// First parameter is the object, second is the method argument
The first String parameter becomes the object; any additional parameters become method arguments.
Key Takeaway: Use ClassName::instanceMethod when your lambda takes an object as its first parameter and calls an instance method on it—Java automatically wires the parameter to be the method's target object.