Collectors.toSet() is a collector that gathers stream elements into a Set, automatically discarding duplicates in the process.
Key Points: • collect(Collectors.toSet()) uses the elements' equals()/hashCode() to deduplicate, just like any Set implementation. • The specific Set implementation returned isn't guaranteed - typically a HashSet, so iteration order isn't preserved. • For an ordered, deduplicated result, use Collectors.toCollection(LinkedHashSet::new) instead. • This is a simpler alternative to distinct().collect(toList()) when you specifically need Set semantics rather than a list. • Since Sets don't allow duplicates, converting a list with repeated values directly shrinks the resulting collection size.
Example: Given the list [1, 2, 2, 3, 3, 3], collecting into a Set produces {1, 2, 3}, with duplicates removed and no guaranteed ordering.
Code Example:
Set<Integer> uniqueNumbers = numbers.stream()
.collect(Collectors.toSet());Interview Tip: A concise interview answer is:
"Collecting a stream with Collectors.toSet() gathers the elements into a Set, which removes duplicates based on equals()/hashCode() as a side effect of Set semantics. If I need a predictable iteration order too, I use Collectors.toCollection(LinkedHashSet::new) instead."