Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Collectors.toSet() Explained

Learn how to use Java's Collectors.toSet() to collect stream elements into a Set, including duplicate handling, ordering, performance, and alternatives.

~4 min readJava
#Java Streams#Collectors#Set#Functional Programming
Java stream elements being collected into a set, illustrating duplicate removal and set behavior

Collectors.toSet() collects the elements of a Java Stream into a Set. It returns a Collector defined in java.util.stream.Collectors since Java 8, and it is the simplest way to produce a set from a stream without manually managing a collection.

What Collectors.toSet() Does

The toSet() method returns a Collector that gathers stream elements into a Set. The API contract does not guarantee a specific implementation; in the current OpenJDK implementation it creates a HashSet. In practice, the resulting set has the usual HashSet behavior: no duplicate elements, no guaranteed iteration order, and support for at most one null element.

Here is a minimal example:

java
Set<String> names = Stream.of("Alice", "Bob", "Alice") .collect(Collectors.toSet());

After execution, names contains only "Alice" and "Bob". The duplicate "Alice" is removed because a Set cannot contain duplicate elements. This behavior is often the primary reason developers choose toSet() over toList().

Basic Usage with Streams

The typical use case is converting a stream of elements into a set for further processing, such as checking membership or removing duplicates. For example, you might collect a stream of IDs into a set to quickly test whether a given ID exists.

java
Set<Integer> ids = orderItems.stream() .map(OrderItem::getProductId) .collect(Collectors.toSet());

The Collector works with any stream source, including collections, arrays, or generated values.

Duplicate Handling and Ordering

Because toSet() commonly returns a HashSet, duplicates are removed based on the equals() and hashCode() methods of the elements. If you need to preserve the order in which elements appear, toSet() is not suitable because HashSet does not guarantee iteration order. For ordered sets, use toCollection(LinkedHashSet::new).

Consider this example:

java
Set<String> ordered = Stream.of("banana", "apple", "cherry") .collect(Collectors.toCollection(LinkedHashSet::new));

This preserves insertion order while still removing duplicates. If you need sorted order, use toCollection(TreeSet::new).

The lack of ordering guarantees in toSet() can be surprising when you rely on the order of elements for output or further processing. Always check whether order matters before choosing toSet().

Underlying Set Implementation

The contract of Collectors.toSet() does not guarantee a specific Set implementation. The Java documentation states that there are no guarantees on the type, mutability, serializability, or thread-safety of the returned Set. In the current OpenJDK implementation, it returns a HashSet, but that could change in future versions. If your code depends on a particular Set type, use toCollection() with an explicit constructor reference.

java
Set<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new)); Set<String> treeSet = stream.collect(Collectors.toCollection(TreeSet::new));

This gives you full control over the implementation, which is important when you need specific ordering, performance characteristics, or null-handling behavior.

Performance and Memory Considerations

HashSet offers constant-time average complexity for add, contains, and remove operations. When collecting a stream, each element is inserted into the set, and duplicates are discarded. The memory overhead of a HashSet is usually higher than that of a List because of the hash table and stored hash codes. For large datasets, this can be a factor to consider.

If you only need to remove duplicates and do not require the result to remain a set, distinct() followed by toList() may be a simpler pipeline. It is not necessarily more memory-efficient, however: the stream implementation also needs to track elements it has already seen.

Parallel streams work with toSet() because the collector can combine partial results. The HashSet itself is not thread-safe, but the stream framework handles accumulation and combining during the collection operation, so you do not need to synchronize access while collecting. The resulting set is not thread-safe for subsequent operations.

Null Values and Edge Cases

HashSet allows at most one null element. If your stream contains multiple null values, toSet() will keep only one. This is usually acceptable, but if you need to reject null values, you can filter them out before collecting.

java
Set<String> nonNull = stream .filter(Objects::nonNull) .collect(Collectors.toSet());

If you use toCollection(TreeSet::new), note that TreeSet does not allow null elements because it relies on natural ordering or a comparator. Attempting to insert null will throw a NullPointerException. Choose the set implementation based on whether null is a valid value in your domain.

Another edge case is an empty stream. toSet() returns an empty set, which is fine. However, if you need an immutable empty set, use Collections.emptySet() or Set.of() (Java 9+); those are not the result of toSet().

When to Use Alternatives

The decision between toSet(), toList(), and toCollection() depends on your requirements:

RequirementRecommended Collector
Remove duplicates, order not importanttoSet()
Preserve insertion order and remove duplicatestoCollection(LinkedHashSet::new)
Sort elements and remove duplicatestoCollection(TreeSet::new)
Keep duplicates and preserve ordertoList()
Explicit set implementationtoCollection(HashSet::new)

If you need a set that is immutable after creation, toSet() does not guarantee immutability. You can wrap the result with Collections.unmodifiableSet() or use Collectors.toUnmodifiableSet() (Java 10+). The toUnmodifiableSet() method returns a set that cannot be modified, which is safer for API boundaries.

java
Set<String> immutable = stream .collect(Collectors.toUnmodifiableSet());

This method also does not allow null elements, so it is a good choice when you want to enforce non-null constraints.

Compatibility with Java Versions

Collectors.toSet() has been available since Java 8, so it works in all modern Java versions. The toUnmodifiableSet() method was added in Java 10. If you are targeting Java 8 or 9, stick with toSet() and wrap the result manually if immutability is required. The behavior of toSet() has remained stable across versions, but the underlying implementation could change, so do not rely on the specific set type.

When using toSet() with parallel streams, remember that the collector is not CONCURRENT: partial results are accumulated separately and combined by the stream framework. The resulting set is not thread-safe for later use. If you need a thread-safe set, use ConcurrentHashMap.newKeySet() with toCollection().

java
Set<String> concurrent = stream .collect(Collectors.toCollection(ConcurrentHashMap::newKeySet));

This is a niche use case, but it shows how toCollection() gives you flexibility that toSet() does not.

For most everyday scenarios, Collectors.toSet() is the right tool. It is concise, idiomatic, and handles duplicate removal without extra code. Just be aware of its limitations regarding ordering and implementation guarantees, and switch to toCollection() when those constraints matter.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.