Home » Java Tutorial » Set in Java Collection Framework – A Complete Guide

Set in Java Collection Framework – A Complete Guide

Java is a powerful programming language, and one of its strongest areas is its Collection Framework. This framework helps us manage groups of objects with ease. One of the most important interfaces in this framework is the Set interface.

In this tutorial, we will learn everything about Set in Java – what it is, how it works, different types of sets, real-life examples, and code snippets to understand each concept clearly.

What is a Set in Java?

A Set in Java is a collection that does not allow duplicate elements. It models the mathematical set abstraction and is part of the java.util package.

Key Characteristics of a Set:

  • Does not allow duplicate elements.
  • The order of elements is not guaranteed (in most implementations).
  • It can contain null (but only once).

Syntax:

Set<Type> setName = new HashSet<>();

Set Interface Hierarchy

          Collection
              ↑
             Set
              ↑
  ┌───────────┼───────────────┐
  ↓           ↓               ↓
HashSet   LinkedHashSet   TreeSet

Each of the above classes implements the Set interface in a different way.

When to Use Set?

Use a Set when:

  • You want to store unique items.
  • You don’t care about the order (use HashSet).
  • You want to maintain insertion order (use LinkedHashSet).
  • You want to keep elements sorted (use TreeSet).

Common Methods in Set Interface

  1. add() – Adds a new guest to the list. Duplicates are ignored.
  2. addAll() – Adds multiple guests at once, like VIPs.
  3. contains() – Checks if someone is on the guest list.
  4. size() – Tells how many people are invited.
  5. remove() – Removes a guest who can’t attend.
  6. isEmpty() – Checks if there’s anyone on the list.
  7. iterator() – Helps go through the list and print each guest.
  8. clear() – Removes all guests from the list.

Example: Guest List using HashSet in Java

In this example, we are going to explore how different Set methods work in Java using a real-world scenario — managing a guest list for a private event. A Set in Java is a collection that does not allow duplicate elements, which makes it perfect for cases like invitations where no person should be invited more than once.

We’ll walk through each method one by one with code examples, so you can clearly understand what each method does and how it’s useful in real applications.

1️⃣ add(E e) – Adds a new guest to the list (ignores duplicates)

Set<String> guestList = new HashSet<>();
guestList.add("Alice");
guestList.add("Bob");
guestList.add("Charlie");
guestList.add("Alice"); // Duplicate, won't be added

System.out.println("Guest List: " + guestList);

Output

[Alice, Bob, Charlie]

📌 Duplicates like “Alice” are ignored automatically in a Set.

2️⃣ addAll(Collection<? extends E> c) – Adds multiple guests at once

List<String> vipGuests = Arrays.asList("Diana", "Edward");
guestList.addAll(vipGuests);

System.out.println("After Adding VIP Guests: " + guestList);

Output

[Alice, Bob, Charlie, Diana, Edward]

📌 Use addAll() to add an entire collection like VIP guests.

3️⃣ contains(Object o) – Checks if someone is on the guest list

System.out.println("Is Bob invited? " + guestList.contains("Bob"));     // true
System.out.println("Is Frank invited? " + guestList.contains("Frank")); // false

Output

Is Bob invited? true
Is Frank invited? false

📌 Returns true if the element exists in the set.

4️⃣ size() – Returns the total number of invited guests

System.out.println("Total Guests: " + guestList.size());

Output

5

📌 Tells how many unique guests are currently in the list.

5️⃣ remove(Object o) – Removes a guest from the list

guestList.remove("Charlie");
System.out.println("After Removing Charlie: " + guestList);

Output

[Alice, Bob, Diana, Edward]

📌 Removes a specific guest if they’re present.

6️⃣ isEmpty() – Checks if the guest list is empty

System.out.println("Is the guest list empty? " + guestList.isEmpty());

Output

false

📌 Returns true only if the set contains no elements.

7️⃣ iterator() – Iterates through all guests in the set

Iterator<String> iterator = guestList.iterator();
System.out.println("Guest List:");
while (iterator.hasNext()) {
    System.out.println("- " + iterator.next());
}

Output

Guest List:
- Diana
- Alice
- Bob
- Charlie

📌 Helpful when you want to loop through all guests manually.

8️⃣ clear() – Clears all guests from the list

guestList.clear();
System.out.println("Guest List after clearing: " + guestList); // []
System.out.println("Is guest list empty now? " + guestList.isEmpty()); // true

Output

Guest List after clearing: []
Is guest list empty now? true

📌 Completely empties the set.

Types of Set in Java

Java provides three main implementations of the Set interface:

1. HashSet

  • Based on hash table.
  • Does not maintain insertion order.
  • Allows one null value.
  • Very fast for operations like add, remove, contains.

Example:

import java.util.*;

public class HashSetExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Apple"); // duplicate

        System.out.println("Fruits: " + fruits);
    }
}

Output might be:

Fruits: [Banana, Apple, Mango]

(Note: Order is not guaranteed.)

2. LinkedHashSet

  • Based on hash table + linked list.
  • Maintains insertion order.
  • Slower than HashSet but predictable ordering.

Example:

import java.util.*;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        Set<String> cities = new LinkedHashSet<>();
        cities.add("Delhi");
        cities.add("Mumbai");
        cities.add("Chennai");
        cities.add("Delhi"); // duplicate

        System.out.println("Cities: " + cities);
    }
}

Output:

Cities: [Delhi, Mumbai, Chennai]

3. TreeSet

  • Based on Red-Black Tree.
  • Maintains sorted order (natural or custom).
  • Does not allow null.
  • Slower than HashSet.

Example:

import java.util.*;

public class TreeSetExample {
    public static void main(String[] args) {
        Set<Integer> numbers = new TreeSet<>();
        numbers.add(50);
        numbers.add(20);
        numbers.add(10);
        numbers.add(30);

        System.out.println("Sorted Numbers: " + numbers);
    }
}

Output:

Sorted Numbers: [10, 20, 30, 50]

Real-life Examples of Using Set

  1. Store unique usernames for an application.
  2. Track visited pages in a browser session.
  3. Remove duplicate entries from a list.

Iterating Through a Set

You can use for-each loop or Iterator to traverse a Set.

Using for-each:

Set<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");

for(String color : colors) {
    System.out.println(color);
}

Using Iterator:

Iterator<String> it = colors.iterator();
while(it.hasNext()) {
    System.out.println(it.next());
}

Things to Remember

  • You cannot access elements using an index in a Set.
  • Set is an interface; you cannot instantiate it directly.
  • Duplicates are automatically ignored when using add().

Set vs List in Java

FeatureSetList
Allows duplicates❌ No✅ Yes
Maintains orderDepends on type✅ Yes
Access by index❌ No✅ Yes
PerformanceFaster for searchSlower

Converting Between Set and List

List to Set (Remove Duplicates):

List<String> list = Arrays.asList("A", "B", "A", "C");
Set<String> set = new HashSet<>(list);

Set to List:

Set<String> set = new HashSet<>();
set.add("X");
set.add("Y");
List<String> list = new ArrayList<>(set);

Practice Question

Write a program that takes a list of names and prints the unique names in sorted order.

Sample Input:

["Alice", "Bob", "Alice", "David", "Bob"]

Sample Output:

[Alice, Bob, David]

Hint: Use TreeSet.

Summary

  • A Set is a collection that contains no duplicate elements.
  • Main implementations: HashSet, LinkedHashSet, TreeSet.
  • Choose your implementation based on whether you need order or sorting.
  • Perfect for use cases like unique elements, lookup, and removing duplicates.

Final Words

Understanding Set is essential for every Java developer. Whether you are preparing for an interview, building real-world applications, or writing clean code, Sets help you ensure data uniqueness efficiently.

💬 If you’re just starting out, practice small programs using HashSet, LinkedHashSet, and TreeSet to understand the differences