Course contentsShow
← Java
Lesson 652 of 2,87015. Nested and Inner ClassesFree lesson

Lambda Conversions with Parameters and Return Values

Migrating anonymous classes with method parameters and return types to lambda syntax.

Lambda Conversions with Parameters and Return Values

What You'll Learn

You'll learn how to convert anonymous classes that take parameters and return values into clean, concise lambda expressions.


From Anonymous Classes to Lambdas with Parameters

In the previous lesson, you saw how to replace simple anonymous classes with lambdas. Now let's handle methods that accept parameters and return values.

Recall that when implementing a functional interface with an anonymous class, you must declare the full method signature:

Comparator<String> comp = new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
};

With lambda syntax, Java infers the parameter types from the interface definition. You can simplify this dramatically:

Comparator<String> comp = (s1, s2) -> s1.length() - s2.length();

Notice what disappeared: the new Comparator<String>() boilerplate, the method name compare, the parameter types String, the return type int, and the return keyword (for single-expression lambdas).


The Pattern

Anonymous class:

InterfaceName var = new InterfaceName() {
    @Override
    public ReturnType methodName(ParamType param) {
        return expression;
    }
};

Lambda equivalent:

InterfaceName var = (param) -> expression;

The lambda takes the same parameters and returns the same type—Java figures it all out from the interface.


Key Takeaway:
When converting anonymous classes with parameters and return values to lambdas, you only keep the parameter names and the expression—Java infers everything else from the functional interface signature.