public
, private
or protected
.
forEach
, map
, filter
, etc.
Runnable
) directly as a lambda.
->
(lambda operator).
(parameters) -> expression
OR
(parameters) -> { statements }
@FunctionalInterface
interface MyInterface
{
void greet(String name);
}
public class MainApp3
{
public static void main(String[] args)
{
// Using Lambda Expression (Shorthand)
MyInterface obj = (String name) -> System.out.println("Hello, " + name + "!");
obj.greet("Deepak"); // Calls the lambda implementation
}
}
Hello, Deepak!
(int no1, int no2) -> {
int sum = no1 + no2;
System.out.println("Sum: " + sum);
return sum; // β
return required when using multiple statements
}
(String name) -> System.out.println("Hello, " + name + "!"); // With type
(name) -> System.out.println("Hello, " + name + "!"); // Without type (preferred)
{}
; but if you have multiple statements, you must use {}
.
(name) -> System.out.println("Hello, " + name) // β
No braces needed
(name) -> { System.out.println("Hello, " + name); } // β
Braces optional (here unnecessary)
name -> System.out.println(name) // β
Parentheses removed
() -> System.out.println("No parameter")
(no) -> no * no
(no1, no2) -> no1 + no2
(no1, no2) -> { return no1 + no2; } // β
return must be written when using {}
(no1, no2) -> no1 + no2 // β
return is implied
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.