Course contentsShow
← Java
Lesson 1744 of 2,87036. Lambda Expressions and Method ReferencesFree lesson

Refactoring Lambdas to Method References

Practice converting simple lambda expressions to method references for cleaner, more concise functional code.

Refactoring Lambdas to Method References

You'll learn how to transform verbose lambda expressions into clean, readable method references.

The Core Idea

When a lambda expression does nothing but call an existing method with its parameter(s), you can replace it with a method reference. This isn't just about saving characters—it's about making your code's intent immediately clear. Instead of writing x -> System.out.println(x), you write System.out.println, letting the method name speak for itself.

Common Refactoring Patterns

Static Method Lambda to Reference

// Before: lambda wrapper
Function<String, Integer> parser = s -> Integer.parseInt(s);

// After: direct method reference
Function<String, Integer> parser = Integer::parseInt;

Instance Method on Specific Object

String prefix = "LOG: ";

// Before: calling method on captured variable
Consumer<String> logger = msg -> prefix.concat(msg);

// After: cleaner method reference
Consumer<String> logger = prefix::concat;

Instance Method on Arbitrary Object

// Before: parameter becomes the receiver
Function<String, String> upper = s -> s.toUpperCase();

// After: parameter is implicitly the object
Function<String, String> upper = String::toUpperCase;

Multi-Parameter Refactoring

// Before: both parameters just passed through
BiFunction<String, String, Boolean> eq = (a, b) -> a.equals(b);

// After: first parameter is receiver, second is argument
BiFunction<String, String, Boolean> eq = String::equals;

When to Refactor

Refactor when the lambda is a pass-through wrapper—it receives parameter(s) and immediately passes them to a method without transformation. Don't force it if you're doing additional logic, parameter reordering, or adding extra arguments.

Key Takeaway: Replace pass-through lambdas with method references to reduce noise and make your functional code's intent crystal clear—the method name becomes your documentation.