Lambda expressions in Java can take multiple parameters, allowing developers to define concise behavior for functional interfaces that require two or more inputs.
Syntax of Lambda with Multiple Parameters
(parameter1, parameter2) -> expression_or_block
If there’s only one statement, you can skip the curly braces {}
. If there’s more than one, use {}
and return
if needed.
Program: Calculate Area of Rectangle
interface RectangleArea { double area(double length, double width); } public class LambdaMultipleParams { public static void main(String[] args) { RectangleArea area = (l, w) -> l * w; System.out.println("Area: " + area.area(5.5, 2.5)); } }
Program: Divide Two Numbers and Handle Division by Zero
interface Divider { String divide(int a, int b); } public class LambdaMultipleParams { public static void main(String[] args) { Divider d = (a, b) -> { if (b == 0) return "Cannot divide by zero"; return "Result: " + (a / b); }; System.out.println(d.divide(10, 2)); System.out.println(d.divide(5, 0)); } }
Program: Compare Two Strings by Length
interface StringComparator { String longer(String s1, String s2); } public class LambdaMultipleParams { public static void main(String[] args) { StringComparator comparator = (s1, s2) -> s1.length() >= s2.length() ? s1 : s2; System.out.println("Longer String: " + comparator.longer("Apple", "Orange")); } }
Lambda expressions with multiple parameters in Java provide a concise and expressive way to implement functional interfaces. They eliminate the need for boilerplate code, such as anonymous inner classes, and improve readability and maintainability.