Collectors.toSet() and Duplicate Handling
What you'll learn: How Collectors.toSet() collects stream elements into a Set while automatically eliminating duplicates based on object equality.
The Core Idea
While Collectors.toList() preserves all elements including duplicates, Collectors.toSet() collects stream elements into a Set — a collection that inherently rejects duplicates. This collector leverages the Set's contract: two elements are considered duplicates if their equals() method returns true and they have the same hashCode().
Think of it like a guest list for an exclusive event: even if someone tries to register twice under the same identity, they only get one entry in the final list.
How Duplicate Elimination Works
The duplicate detection relies entirely on the equals() and hashCode() contracts of the objects in the stream. For built-in types like String and Integer, these methods are already properly implemented. For custom objects, you must ensure these methods are correctly overridden.
When you use toSet(), the collector:
- Creates a new
Set(typically aHashSet) - Adds each element from the stream
- The Set automatically discards any element that
equals()an existing element
Basic Usage
Stream.of("apple", "banana", "apple", "cherry")
.collect(Collectors.toSet());
// Result: a Set containing ["apple", "banana", "cherry"]
Important Considerations
The resulting Set is mutable but makes no guarantees about iteration order (because it's typically a HashSet). If you have five "apple" strings in your stream, only one appears in the final Set. The collector doesn't care which duplicate it keeps — just that duplicates are eliminated.
Key Takeaway: Collectors.toSet() automatically eliminates duplicates by relying on the equals() and hashCode() contracts, making it ideal when you need unique elements from a stream.