In Java, lambda expressions are a feature introduced in Java 8
that allow you to write more concise and expressive code when working with functional interfaces.
Lambda expressions are essentially anonymous functions
that can be used as a replacement for single-method interfaces.
They provide a way to define a behavior or an implementation directly
at the point of use without explicitly implementing a functional interface.
Here's an example to demonstrate the usage of lambda expressions in Java:
import java.util.Arrays;
import java.util.List;
public class LambdaExample {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("Apple", "Banana", "Orange", "Mango");
// Using lambda expression to iterate over the list
fruits.forEach(fruit -> System.out.println(fruit));
// Using lambda expression with multiple statements
fruits.forEach(fruit -> {
String formattedFruit = fruit.toUpperCase();
System.out.println("Formatted: " + formattedFruit);
});
// Using lambda expression with parameters
fruits.forEach((String fruit) -> System.out.println(fruit));
// Using lambda expression with explicit data type
fruits.forEach((String fruit) -> {
String formattedFruit = fruit.toUpperCase();
System.out.println("Formatted: " + formattedFruit);
});
}
}
In this example, we have a list of fruits, and we use the 'forEach' method to iterate over the elements of the list.
Instead of using a traditional for loop or an iterator, we use a lambda expression as the argument to 'forEach'.
The lambda expression '(fruit -> System.out.println(fruit))' is essentially an implementation of the 'Consumer' functional interface, which has a single method 'accept' that takes a parameter of type 'T'(in this case, 'String') and returns 'void'. The lambda expression provides the implementation of the 'accept' method.
Lambda expressions can be written in different forms depending on the context and the number of parameters.
They can also be used with functional interfaces that have multiple arguments.
It's important to note that lambda expressions are meant to simplify the code and make it more readable.
They are particularly useful when working with collections, streams, and functional programming concepts in Java.
'Language > Java' 카테고리의 다른 글
Arrays.asList() vs ArrayList (0) | 2023.06.19 |
---|---|
Anonymous class (0) | 2023.06.14 |
Array and ArrayList (0) | 2023.05.30 |
Generics (0) | 2023.05.29 |
replace, replaceAll (0) | 2023.05.25 |