How to Filter a Set in Java

1. Introduction

Filtering a set in Java involves selecting elements that satisfy certain conditions from a set. This operation is common in many programming tasks, such as data processing or collection manipulation. Java provides various ways to perform filtering, including using loops, the Stream API introduced in Java 8, and, if using external libraries is an option, utilities like Apache Commons Collections. This blog post will explore different methods to filter a set in Java.

2. Program Steps

1. Create a set of integers.

2. Filter the set to include only even numbers using a for-loop and a temporary set.

3. Filter the set to include only even numbers using the Stream API.

4. (Optional) Filter the set using Apache Commons Collections, if external libraries are an option.

3. Code Program

import java.util.*;
import java.util.stream.Collectors;

public class FilterSet {
    public static void main(String[] args) {
        // Creating a set of integers
        Set<Integer> numbers = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

        // Method 1: Filtering using a for-loop
        Set<Integer> evenNumbersUsingLoop = new HashSet<>();
        for (Integer number : numbers) {
            if (number % 2 == 0) {
                evenNumbersUsingLoop.add(number);
            }
        }

        // Method 2: Filtering using the Stream API
        Set<Integer> evenNumbersUsingStream = numbers.stream()
                                                      .filter(number -> number % 2 == 0)
                                                      .collect(Collectors.toSet());

        // Displaying the original set
        System.out.println("Original set: " + numbers);

        // Displaying the filtered sets
        System.out.println("Even numbers using loop: " + evenNumbersUsingLoop);
        System.out.println("Even numbers using Stream API: " + evenNumbersUsingStream);
    }
}

Output:

Original set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even numbers using loop: [2, 4, 6, 8, 10]
Even numbers using Stream API: [2, 4, 6, 8, 10]

Explanation:

1. The program begins by creating a HashSet named numbers containing integers from 1 to 10. HashSet is used to ensure unique elements, and the order of elements in the output may vary because sets do not maintain order.

2. The first filtering method uses a for-loop to iterate over each element in the numbers set. It checks if an element is even (using number % 2 == 0) and adds even numbers to a new set named evenNumbersUsingLoop.

3. The second filtering method uses the Stream API. The numbers set is converted into a stream using numbers.stream(), filtered to select only even numbers, and collected back into a set evenNumbersUsingStream using Collectors.toSet().

4. Both evenNumbersUsingLoop and evenNumbersUsingStream sets contain only the even numbers extracted from the original set, demonstrating the output of each filtering method.

5. This example illustrates two approaches to filtering sets in Java, highlighting both the imperative approach using loops and the declarative approach using the Stream API.

Comments