In Java, lambdas are a feature introduced in Java 8 that allow you to treat functionality as a method argument or to create anonymous functions. Lambdas provide a concise way to express instances of single-method interfaces (also known as functional interfaces). Here's how you can use lambdas in Java:
Syntax:The basic syntax of a lambda expression in Java is as follows:
(parameters) -> expression
or
(parameters) -> { statements; }
Where:
-
parameters:
The input parameters for the lambda expression. -
->:
The lambda operator, separates the parameter list from the body of the lambda expression. -
expression
or{ statements; }:
The body of the lambda expression, which can be an expression or a block of statements.
-
Using Lambda with Functional Interface:
Suppose you have a functional interface
MyInterface
with a single abstract methodmyMethod()
:interface MyInterface { void myMethod(); }
You can use a lambda expression to implement this interface:
MyInterface obj = () -> System.out.println("Lambda expression implementation"); obj.myMethod(); // Output: Lambda expression implementation
-
Using Lambda with Parameters:
You can also use lambdas with parameters:
interface AddInterface { int add(int a, int b); }
AddInterface addObj = (int a, int b) -> a + b; System.out.println(addObj.add(3, 5)); // Output: 8
-
Using Lambda with Collections:
Lambdas are often used with collections to perform operations like filtering, mapping, or iterating:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); // Using forEach to iterate through elements numbers.forEach(num -> System.out.println(num)); // Using filter to filter even numbers List<Integer> evenNumbers = numbers.stream() .filter(num -> num % 2 == 0) .collect(Collectors.toList());
-
Using Lambda with Comparator:
You can use lambdas with
Comparator
for sorting:List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David"); // Sorting names in ascending order Collections.sort(names, (name1, name2) -> name1.compareTo(name2));
- Lambdas can only be used with functional interfaces, i.e., interfaces with only one abstract method.
-
Lambdas can capture variables from their enclosing scope, but these variables must be effectively final or explicitly marked as
final
.
These examples demonstrate the basic usage of lambdas in Java. They provide a concise and expressive way to represent functionality as objects.