In Java, a Set is a collection that:
- Stores unique elements (no duplicates allowed).
- Does not guarantee order (depending on the implementation).
- Is part of the Java Collections Framework (
java.util
package).
🔑 Main Set Implementations
1. HashSet
- Backed by a hash table.
- Elements are unordered.
- Fast for
add()
,remove()
,contains()
(O(1) on average).
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("Orange");
set.add("Apple"); // Duplicate ignored
System.out.println(set); // Output: [Apple, Banana, Orange] (order may vary)
}
}
2. LinkedHashSet
- Maintains insertion order.
- Slightly slower than
HashSet
due to extra ordering overhead.
Set<String> set = new LinkedHashSet<>();
set.add("One");
set.add("Two");
set.add("Three");
System.out.println(set); // Output: [One, Two, Three]
3. TreeSet
- Implements SortedSet (elements stored in ascending order).
- Backed by a Red-Black Tree.
- Operations like
add()
,remove()
, andcontains()
are O(log n).
Set<Integer> set = new TreeSet<>();
set.add(30);
set.add(10);
set.add(20);
System.out.println(set); // Output: [10, 20, 30]
🔧 Common Methods of Set
add(E e)
→ Adds element if not already present.remove(Object o)
→ Removes specified element.contains(Object o)
→ Checks if element exists.size()
→ Returns number of elements.isEmpty()
→ Checks if set is empty.clear()
→ Removes all elements.addAll(Collection c)
→ Union of sets.retainAll(Collection c)
→ Intersection of sets.removeAll(Collection c)
→ Difference of sets.
✅ Example: Union, Intersection, Difference
import java.util.*;
public class SetOperations {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));
// Union
Set<Integer> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("Union: " + union); // [1, 2, 3, 4, 5, 6]
// Intersection
Set<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Intersection: " + intersection); // [3, 4]
// Difference
Set<Integer> difference = new HashSet<>(set1);
difference.removeAll(set2);
System.out.println("Difference: " + difference); // [1, 2]
}
}