Course contentsShow
← Java
Lesson 1550 of 2,87034. Collectors in DepthFree lesson

Collectors.toSet(): Collecting into a Set

Understand how toSet() collects elements into a HashSet, removing duplicates and when uniqueness matters.

Collectors.toSet(): Collecting into a Set

What you'll learn: How to collect stream elements into a Set to automatically eliminate duplicates and ensure uniqueness.

The Core Idea

While Collectors.toList() preserves all elements including duplicates, Collectors.toSet() collects stream elements into a Set — specifically a HashSet by default. The key behavior here is automatic duplicate removal: if your stream contains the same element multiple times, the resulting Set will contain only one instance.

Think of it like dropping marbles into a jar with a uniqueness filter: if you try to drop a marble that's already inside, it simply doesn't get added.

When Uniqueness Matters

Use toSet() when:

  • You need to ensure each element appears only once
  • Order doesn't matter (unlike lists)
  • You're processing data where duplicates are noise or redundant

Basic Usage

List<String> fruits = List.of("apple", "banana", "apple", "cherry", "banana");
Set<String> uniqueFruits = fruits.stream()
                                  .collect(Collectors.toSet());
// Result: [apple, banana, cherry] (order may vary)

How Duplicates Are Identified

The Set uses each object's equals() and hashCode() methods to determine uniqueness. Two objects are considered duplicates if equals() returns true.

List<Integer> numbers = List.of(1, 2, 2, 3, 3, 3);
Set<Integer> uniqueNumbers = numbers.stream()
                                    .collect(Collectors.toSet());
// Result: [1, 2, 3]

Important Characteristics

  • No guaranteed order: HashSet doesn't maintain insertion order
  • Null handling: One null is allowed (subsequent nulls are duplicates)
  • Performance: Typically O(1) for add operations

Key Takeaway: Use Collectors.toSet() when you need a collection of unique elements and don't care about order — it's your automatic duplicate-removal tool in stream pipelines.