1. Introduction
Filtering a List in Java can be done easily using the Stream API introduced in Java 8. The filter method of the Stream interface takes a Predicate and retains only those elements that satisfy the given predicate, essentially filtering the List based on a condition.
2. Program Steps
1. Create a List of integers.
2. Print the original List.
3. Use the stream() method to convert the List to a Stream.
4. Use the filter() method to filter the Stream based on a condition.
5. Collect the result back into a new List.
6. Print the filtered List.
3. Code Program
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterList {
public static void main(String[] args) {
// Step 1: Create a List of integers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Step 2: Print the original List
System.out.println("Original List: " + numbers);
// Step 3: Convert the List to a Stream
// Step 4: Use the filter() method to filter the Stream based on a condition
// Step 5: Collect the result back into a new List
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// Step 6: Print the filtered List
System.out.println("Filtered List (Even Numbers): " + evenNumbers);
}
}
Output:
Original List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Filtered List (Even Numbers): [2, 4, 6, 8, 10]
4. Step By Step Explanation
Step 1: A List of integers named numbers is created and initialized with numbers from 1 to 10.
Step 2: The original List, numbers, is printed to the console.
Step 3: The List numbers is converted to a Stream using the stream() method.
Step 4: The filter() method is used on the Stream to retain only the even numbers. The filter() method takes a Predicate as an argument, which in this case, is a lambda expression n -> n % 2 == 0 specifying the condition for a number to be even.
Step 5: The filtered Stream is collected back into a new List named evenNumbers using the collect() method and Collectors.toList().
Step 6: Finally, the filtered List containing only even numbers, evenNumbers, is printed to the console.