Junior
What are lambda expressions in Java?
sobes.tech AI
Answer from AI
A lambda expression is a concise form for an anonymous function that implements methods of a functional interface.
Structure: (parameters) -> { expression body }.
| Part | Description | Examples |
|---|---|---|
parameters |
List of parameters, can be empty. Types may be omitted (inferred). | ()<br>x<br>(x, y)<br>(int x, String y) |
-> |
Arrow operator. Separates parameters and body. | -> |
expression body |
Lambda body. Can be an expression or a block of code. | x * x<br>{ System.out.println(x); } |
Examples of usage:
-
Implementing functional interfaces:
import java.util.function.Consumer; // Using traditional anonymous class Consumer<String> consumerAnon = new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } }; consumerAnon.accept("Traditional anonymous class"); // Using lambda expression Consumer<String> consumerLambda = s -> System.out.println(s); consumerLambda.accept("Lambda expression"); -
Working with Streams API:
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); // Filtering even numbers with lambda List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); System.out.println(evenNumbers); // Output: [2, 4] // Transforming numbers to their squares List<Integer> squares = numbers.stream() .map(n -> n * n) .collect(Collectors.toList()); System.out.println(squares); // Output: [1, 4, 9, 16, 25]
Advantages:
- Reduces code compared to anonymous classes.
- Improves readability for simple operations.
- Convenient for use with Streams API and other APIs oriented towards functional programming.