Using Method References with ifPresent
You'll learn how method references can make your ifPresent calls dramatically more concise and readable.
The Power of Brevity
In the previous lesson, you saw how ifPresent accepts a Consumer to operate on a value when it's present. When that operation is simply calling a single method, method references let you eliminate lambda boilerplate entirely.
Instead of writing a lambda that merely forwards its parameter to a method, you can reference the method directly. This makes your intent crystal clear at a glance.
Common Patterns with Method References
Static Method Reference
Optional<String> message = Optional.of("Warning: Low disk space");
// Lambda style
message.ifPresent(msg -> System.out.println(msg));
// Method reference style
message.ifPresent(System.out::println);
Both do exactly the same thing, but the method reference reads more naturally—"if present, print it to System.out."
Instance Method on Arbitrary Object
Optional<String> email = Optional.of(" user@example.com ");
// Lambda style
email.ifPresent(e -> e.trim()); // (though trim's result isn't used)
// Method reference for processing
email.ifPresent(String::trim);
Instance Method on Specific Object
List<String> results = new ArrayList<>();
Optional<String> result = Optional.of("Success");
// Lambda style
result.ifPresent(r -> results.add(r));
// Method reference style
result.ifPresent(results::add);
The method reference results::add is beautifully concise—it says "if present, add it to results" without ceremony.
Key Takeaway: Method references transform ifPresent calls from verbose lambda expressions into clear, single-purpose statements that directly express what operation should happen when a value exists.