1. Introduction
Filtering a Set in Java can be accomplished 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. This is useful for filtering a Set based on a condition.
2. Program Steps
1. Create a Set of integers.
2. Print the original Set.
3. Use the stream() method to convert the Set to a Stream.
4. Use the filter() method to filter the Stream based on a condition.
5. Collect the result back into a new Set.
6. Print the filtered Set.
3. Code Program
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;
public class FilterSet {
public static void main(String[] args) {
// Step 1: Create a Set of integers
Set<Integer> numbers = new HashSet<>(Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
// Step 2: Print the original Set
System.out.println("Original Set: " + numbers);
// Step 3: Convert the Set 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 Set
Set<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toSet());
// Step 6: Print the filtered Set
System.out.println("Filtered Set (Even Numbers): " + evenNumbers);
}
}
Output:
Original Set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Filtered Set (Even Numbers): [2, 4, 6, 8, 10]
4. Step By Step Explanation
Step 1: A Set of integers named numbers is created and initialized with numbers from 1 to 10.
Step 2: The original Set, numbers, is printed to the console.
Step 3: The Set 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 Set named evenNumbers using the collect() method and Collectors.toSet().
Step 6: Finally, the filtered Set containing only even numbers, evenNumbers, is printed to the console.