Convert Stream to Set in Java

1. Introduction

Converting a Stream to a Set in Java is a common requirement when you want to eliminate duplicate elements from a collection or when you need the characteristics of a Set after processing data with a Stream. The Java Stream API, introduced in Java 8, facilitates complex data processing operations in a concise and readable manner. This blog post will explore converting a Stream to a Set, using the Collectors utility to gather the processed elements into a Set, which inherently removes duplicates.

2. Program Steps

1. Create a Stream of elements, potentially containing duplicates.

2. Use the collect method along with Collectors.toSet() to convert the Stream to a Set, automatically removing duplicates.

3. Display the resulting Set.

3. Code Program

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

public class StreamToSet {
    public static void main(String[] args) {
        // Step 1: Creating a Stream of elements
        Stream<String> stream = Stream.of("Apple", "Banana", "Cherry", "Apple", "Date", "Banana");

        // Step 2: Converting Stream to Set
        Set<String> set = stream.collect(Collectors.toSet());

        // Step 3: Displaying the resulting Set
        System.out.println("Set from Stream: " + set);
    }
}

Output:

Set from Stream: [Apple, Banana, Cherry, Date]

Explanation:

1. The program begins by creating a Stream<String> containing a sequence of fruit names. Notably, this sequence includes duplicates ("Apple" and "Banana" appear more than once).

2. To convert this Stream into a Set, the collect method of the Stream API is used. This method requires a Collector that specifies the desired collection type and behavior. Collectors.toSet() is provided, which accumulates the elements of the Stream into a new Set. One key property of a Set is that it contains no duplicate elements, so Collectors.toSet() automatically removes any duplicates found in the Stream.

3. The resulting Set<String> is stored in the variable set, which now contains the unique elements from the original Stream.

4. Finally, the Set is printed to the console, showcasing the unique elements that were in the Stream. This demonstrates the effectiveness of using a Stream to process data and Collectors.toSet() to collect the results into a Set, eliminating duplicates in the process.

5. This example highlights a practical application of the Stream API and Collectors for data processing and collection transformation in Java.

Comments