DEV Community

Cover image for Set in Java
Vidya
Vidya

Posted on

Set in Java

What is a Set in Java Collections?
A Set is a collection in Java that:
--> Does not allow duplicate elements
--> Does not guarantee index (no ordering like List)
--> Stores only unique values

It is part of java.util.Set interface.

Main Types of Set
1. HashSet
--> No order maintained
--> Fast performance
--> Allows one null

Example

import java.util.*;

public class HashSetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();

        set.add("Apple");
        set.add("Banana");
        set.add("Apple"); // duplicate ignored
        set.add("Mango");

        System.out.println(set);
    }
}      output:[Apple, Banana, Mango]
Enter fullscreen mode Exit fullscreen mode

2. LinkedHashSet
--> Maintains insertion order
--> No duplicates allowed
Example

import java.util.*;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        Set<Integer> set = new LinkedHashSet<>();

        set.add(10);
        set.add(30);
        set.add(20);
        set.add(10); // ignored

        System.out.println(set);
    }
}         output:[10, 30, 20]
Enter fullscreen mode Exit fullscreen mode

3. TreeSet
--> Stores elements in sorted (ascending) order
--> No duplicates allowed
--> Slower than HashSet

Example:

 import java.util.*;

public class TreeSetExample {
    public static void main(String[] args) {
        Set<Integer> set = new TreeSet<>();

        set.add(50);
        set.add(10);
        set.add(30);
        set.add(20);

        System.out.println(set);
    }
}         output:[10, 20, 30, 50]
Enter fullscreen mode Exit fullscreen mode

Key Features of Set
--> Unique elements only
--> No index (no get(0) like List)
--> Used in removing duplicates
--> Supports iteration (for-each loop)

Top comments (0)