1. Introduction
In Java, the Stream API is a powerful tool that allows you to process sequences of elements (e.g., collections) in a functional style. A Set is a collection that does not contain duplicate elements. Converting a Stream to a Set can be useful when you have a sequence of elements and you want to eliminate duplicates and don’t care about the order.
2. Program Steps
1. Import the necessary libraries.
2. Create a Stream of elements, which may contain duplicates.
3. Convert the Stream to a Set using the collect method and Collectors.toSet().
4. Display the elements of the Set.
3. Code Program
// Step 1: Import the necessary libraries
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamToSetExample {
public static void main(String[] args) {
// Step 2: Create a Stream of elements
Stream<String> animalStream = Stream.of("Cat", "Dog", "Elephant", "Cat", "Dog");
// Step 3: Convert the Stream to a Set
Set<String> animalSet = animalStream.collect(Collectors.toSet());
// Step 4: Display the elements of the Set
animalSet.forEach(System.out::println);
}
}
Output:
Cat Dog Elephant
4. Step By Step Explanation
Step 1: The necessary libraries for handling sets, streams, and collectors are imported.
Step 2: A Stream of strings representing animal names is created using the Stream.of method. Note that this Stream contains duplicate elements.
Step 3: The Stream is converted to a Set using the collect method along with Collectors.toSet(). This results in a new Set object, animalSet, which holds all the unique elements of the original Stream.
Step 4: Each element of the Set is printed to the console using the forEach method and method reference System.out::println. The output contains only the unique elements, demonstrating that duplicates have been removed.