Java Set

Introduction

The Java Set interface is one of the core components of the Java Collection Framework. It is used to store a collection of unique elements, meaning it does not allow duplicate values. Unlike the List interface, which maintains elements in an ordered sequence and allows duplicates, a Set focuses on ensuring that every element is distinct.

The Set interface belongs to the java.util package and extends the Collection interface. Since Set is an interface, it cannot be instantiated directly. Java provides several implementations of the Set interface, such as HashSet, LinkedHashSet, TreeSet, and EnumSet, each designed for different use cases.

Sets are widely used in applications where uniqueness is important, such as storing usernames, email addresses, product IDs, employee IDs, unique tags, and database keys.

What is Java Set?

A Set is a collection that stores unique elements. If you try to add a duplicate element, the Set simply ignores it without throwing an error.

For example:

Input:


Java
Python
Java
C++
Python

Output:


Java 
Python
C++

Notice that duplicate values (Java and Python) are stored only once.

Key Characteristics

  • Does not allow duplicate elements
  • Stores unique values
  • Dynamic size
  • Part of the Java Collection Framework
  • Supports Generics
  • Different implementations provide different ordering behaviors
  • Allows at most one null element in some implementations (such as HashSet and LinkedHashSet)

Java Set Hierarchy


Iterable
    │
Collection
    │
Set
    │
├── HashSet
├── LinkedHashSet
├── TreeSet
├── EnumSet
└── CopyOnWriteArraySet

Popular Implementations

  • HashSet – Fastest for general-purpose use; no guaranteed order.
  • LinkedHashSet – Maintains insertion order.
  • TreeSet – Stores elements in sorted order.
  • EnumSet – Optimized for enum values.

Features of Java Set

Some important features include:

  • Stores unique elements only
  • Automatically prevents duplicates
  • Dynamic resizing
  • Supports Generics
  • Multiple implementations for different requirements
  • Efficient searching in most implementations
  • Can store heterogeneous objects (without Generics)
  • Integrates with the Java Collection Framework

Syntax

Import Statement


import java.util.Set;
import java.util.HashSet;

or


import java.util.*;

Creating a Set

Using HashSet:


Set<String> languages = new HashSet<>();

Using LinkedHashSet:


Set<String> languages = new LinkedHashSet<>();

Using TreeSet:


Set<String> languages = new TreeSet<>();

Common Methods of Set

Method Description
addFirst() Adds an element
remove() Removes an element
contains() Checks whether an element exists
size() Returns the number of elements
isEmpty() Checks whether the Set is empty
clear() Removes all elements
iterator() Returns an iterator for traversal
addAll() Adds all elements from another collection
removeAll() Removes matching elements
retainAll() Keeps only common elements

Example 1: Creating a HashSet


import java.util.*;

public class HashSetExample {

    public static void main(String[] args) {

        Set<String> languages = new HashSet<>();

        courses.add("Java");
        courses.add("Python");
        courses.add("Spring Boot");

        System.out.println(courses);
    }
}

Output

[Java, Python, Spring Boot]

Note: The order may vary because HashSet does not maintain insertion order.

Example 2: Duplicate Elements


import java.util.*;

public class DuplicateExample {

    public static void main(String[] args) {

         Set<integer> languages = new HashSet<>();

        numbers.add(10);
        numbers.add(20);
        numbers.add(10);
        numbers.add(30);

        System.out.println(numbers);
    }
}

Output

[10, 20, 30]

The duplicate value 10 is ignored automatically.

Example 3: Checking an Element


import java.util.*;

public class ContainsExample {

    public static void main(String[] args) {

      Set<String> fruits = new HashSet<>()

        fruits.add("Apple");
        fruits.add("Banana");

        System.out.println(fruits.contains("Banana"));
    }
}

Output

true

Example 4: Removing an Element


import java.util.*;

public class RemoveExample {

    public static void main(String[] args) {

       Set<String> cities = new HashSet<>()

        cities.add("Delhi");
        cities.add("Mumbai");
        cities.add("Jaipur");

        cities.remove("Mumbai");

        System.out.println(cities);
    }
}

Output

[Delhi, Jaipur]

Example 5: Iterating Through a Set


import java.util.*;

public class LoopExample {

    public static void main(String[] args) {

         Set<String> skills = new HashSet<>()

        skills.add("Java");
        skills.add("Spring");
        skills.add("Hibernate");

        for(String skill : skills){
            System.out.println(skill);
        }
    }
}

Output

Java
Spring
Hibernate

Types of Set Implementations

1. HashSet

Features

  • No duplicate elements
  • Does not maintain insertion order
  • Fastest implementation
  • Allows one null value

Best For

  • General-purpose storage
  • Fast searching
  • High-performance applications

2. LinkedHashSet

Features

  • Maintains insertion order
  • No duplicates
  • Slightly slower than HashSet
  • Allows one null value

Best For

  • Applications where insertion order matters

3. TreeSet

Features

  • Stores elements in sorted order
  • No duplicate elements
  • Does not allow null
  • Uses a Red-Black Tree internally

Best For

  • Sorted collections
  • Ranking systems
  • Leaderboards

HashSet vs LinkedHashSet vs TreeSet

Feature HashSet LinkedHashSet LinkedHashSet
Duplicate Elements No No No
Insertion Order No Yes No
Sorted Order No No Yes
Allows Null Yes (one) Yes (one) No
Performance Fastest Fast Slower

Time Complexity

lower
Operation HashSet LinkedHashSet TreeSet
add() O(1) O(1) O(log n)
remove() O(1) O(1) O(log n)
contains() O(1) O(1) O(log n)

Real-life Example

Imagine you’re developing an online learning platform.

Students enroll in courses using their email addresses.

If a student accidentally submits the same email multiple times, the system should register it only once.

Using a Set ensures uniqueness automatically.

Other real-world applications include:

  • Usernames
  • Email addresses
  • Employee IDs
  • Product IDs
  • Unique hashtags
  • Country codes
  • Database primary keys
  • Permission management systems

Advantages of Java Set

  • Automatically removes duplicate entries
  • Efficient searching (especially with HashSet)
  • Dynamic size
  • Supports multiple implementations
  • Supports Generics
  • Easy to use
  • Suitable for unique data storage
  • Well integrated with the Java Collection Framework

Limitations of Java Set

  • Does not allow duplicate elements
  • Cannot access elements by index
  • Ordering depends on the implementation
  • TreeSet operations are slower than HashSet
  • Some implementations do not allow null values

Common Mistakes

1. Expecting Duplicate Elements


Deque<Integer> set = new Hashset<>();
set.add(10);
set.add(10);
System.out.println(set);

Output:

[10]

The duplicate value is ignored.

2. Assuming HashSet Maintains Order

Incorrect assumption:


Java
Python
C++

Output order may be different because HashSet does not preserve insertion order.

Use LinkedHashSet if insertion order is important.

3. Adding Null to TreeSet


Set<string> set = new Treeset<>();
set.add(null);

This throws a NullPointerException.

4. Forgetting Generics

Incorrect:


Set set = new HashSet();

Correct:


Set<string> set = new Treeset<>();

5. Trying to Access Elements by Index

A Set does not support index-based access like a List.

Incorrect:


set.get(0);

This results in a compilation error because the Set interface has no get() method.

Best Practices

  • Program to the Set interface.

Set<string> user = new Hashset<>();
  • Use HashSet for fast lookup and insertion.
  • Use LinkedHashSet when insertion order must be preserved.
  • Use TreeSet when sorted data is required.
  • Always use Generics for type safety.
  • Override equals() and hashCode() correctly when storing custom objects in a HashSet or LinkedHashSet.

Conclusion

The Java Set interface is an essential part of the Java Collection Framework for storing unique elements. It automatically eliminates duplicates, making it ideal for applications that require data uniqueness. With implementations such as HashSet, LinkedHashSet, and TreeSet, developers can choose between high performance, insertion-order preservation, or automatic sorting based on their application’s needs.

Related Java Tutorials