0
0
JavaConceptBeginner · 3 min read

What is Set in Java: Definition, Usage, and Examples

Set in Java is a collection that stores unique elements without any specific order. It does not allow duplicates, making it useful when you want to keep only one copy of each item.
⚙️

How It Works

A Set in Java works like a bag that only accepts unique items. Imagine you have a basket where you put fruits, but you never want to have two apples. If you try to add an apple again, the basket ignores it because it already has one.

Internally, a Set checks each new element to see if it is already present. If it is, the new element is not added. This makes Set different from a list, which can have many copies of the same item.

There are different types of Set in Java, like HashSet, which stores items without order, and TreeSet, which keeps items sorted. But all share the rule of no duplicates.

💻

Example

This example shows how to create a Set, add elements, and see that duplicates are ignored.

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

public class SetExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Apple"); // Duplicate, will not be added
        fruits.add("Orange");

        System.out.println(fruits);
    }
}
Output
[Apple, Banana, Orange]
🎯

When to Use

Use a Set when you need to store items without duplicates and order does not matter. For example:

  • Keeping track of unique user IDs in an app.
  • Storing unique words from a text for analysis.
  • Removing duplicates from a list of items.

If you want to keep items sorted, use TreeSet. If order does not matter and you want fast operations, use HashSet.

Key Points

  • Set stores unique elements only.
  • Duplicates are automatically ignored.
  • No guaranteed order in HashSet, sorted order in TreeSet.
  • Useful for removing duplicates and fast membership checks.

Key Takeaways

A Set in Java stores only unique elements, preventing duplicates.
HashSet is the most common Set implementation with no order guarantee.
Use Set to remove duplicates or track unique items efficiently.
TreeSet keeps elements sorted but may be slower than HashSet.
Sets are ideal when order is not important but uniqueness is.