Filtering Even Numbers In this example, we have a list of numbers from 1 to 10. We define a lambda expression n -> n % 2 == 0
and pass it as a predicate to the filterNumbers
method. The lambda expression checks if a number is even. The filterNumbers
method takes a list of numbers and a Predicate<Integer>
as arguments. It iterates over the numbers and applies the predicate using the test
method. If the predicate returns true
, the number is printed.
Filtering Numbers Greater Than 5 In this part of the example, we reuse the filterNumbers
method to filter numbers greater than 5. We define a different lambda expression n -> n > 5
and pass it as the predicate. This lambda expression checks if a number is greater than 5. Again, the filterNumbers
method iterates over the numbers and applies the predicate, printing the numbers that satisfy the condition.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class LambdasExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Title: Filtering Even Numbers
System.out.println("Filtered Even Numbers:");
filterNumbers(numbers, n -> n % 2 == 0);
// Title: Filtering Numbers Greater Than 5
System.out.println("Filtered Numbers Greater Than 5:");
filterNumbers(numbers, n -> n > 5);
}
private static void filterNumbers(List<Integer> numbers, Predicate<Integer> predicate) {
for (Integer number : numbers) {
if (predicate.test(number)) {
System.out.println(number);
}
}
}
}
These examples demonstrate the flexibility and reusability of lambdas by allowing us to easily define different filtering conditions without duplicating the filtering logic.