Lambda expressions in Java can return values just like regular methods. This makes them ideal for implementing functions that perform a task and return a result, such as calculations, transformations, or comparisons.
Syntax of Lambda with Return Value
(parameters) -> expression
// or with block body
(parameters) -> {
// multiple statements
return result;
}
Code language: JavaScript (javascript)
-
If the lambda has one expression, the result of that expression is automatically returned.
-
If the lambda has multiple statements, you must use the
return
keyword explicitly.
Program: Compare Two Numbers
interface Compare { int max(int a, int b); } public class LambdaReturnExample { public static void main(String[] args) { Compare cmp = (a, b) -> { if (a > b) return a; else return b; }; System.out.println("Max: " + cmp.max(25, 40)); } }
Program : Check Palindrome
interface PalindromeCheck { boolean isPalindrome(String str); } public class LambdaReturnExample { public static void main(String[] args) { PalindromeCheck pc = s -> s.equals(new StringBuilder(s).reverse().toString()); System.out.println("Is Palindrome: " + pc.isPalindrome("madam")); } }
Lambda expressions with return values in Java allow for clean, concise implementations of functional logic. By using either a simple expression or a block of code with a return statement, you can:
-
Replace anonymous classes
-
Simplify business logic
-
Improve readability
These are especially powerful in stream operations and functional programming constructs where operations often need to return transformed or computed results.