Lambda expressions in Java are commonly used with collections to simplify iteration and manipulation of data. They allow developers to express operations on collections more concisely and clearly.
forEach() Method:
The forEach() method in Java is used to iterate over elements of a collection and perform an action for each element. Lambda expressions can be used with the forEach() method to specify the action.
Example using forEach() with Lambda:
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Using forEach() with Lambda Expression
names.forEach(name -> System.out.println("Hello, " + name));
}
}
removeIf() Method:
The removeIf() method in Java is used to remove elements from a collection based on a condition specified by a lambda expression.
Example using removeIf() with Lambda:
import java.util.ArrayList;
import java.util.List;
public class RemoveIfExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
// Using removeIf() with Lambda Expression
numbers.removeIf(num -> num % 2 == 0);
System.out.println(numbers); // Output: [1, 3]
}
}
replaceAll() Method:
The replaceAll() method in Java is used to replace each element in a collection with the result of applying a function specified by a lambda expression.
Example using replaceAll() with Lambda:
import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;
public class ReplaceAllExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry");
// Using replaceAll() with Lambda Expression
List<String> upperCaseWords = words.stream().map(word -> word.toUpperCase()).collect(Collectors.toList());
System.out.println(upperCaseWords); // Output: [APPLE, BANANA, CHERRY]
}
}
Streams and Lambda Expressions:
Lambda expressions are extensively used with Java streams, allowing developers to perform various operations on data such as filtering, mapping, reducing, and more.
Example using Streams and Lambda Expressions:
import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;
public class StreamExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry");
// Using Streams and Lambda Expressions
List<String> filteredWords = words.stream()
.filter(word -> word.startsWith("a"))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(filteredWords); // Output: [APPLE]
}
}
In this example, the stream processes the list of words. The filter() method is used to filter words starting with "a", the map() method converts the words to uppercase, and collect() gathers the results into a list. Lambda expressions make these operations concise and expressive.