Java Collections Essentials — Part 4
There are three components that extend the collection interface i.e List, Queue and Sets. Let’s discuss about Sets.
Set is an interface in Java that represents a collection of unique elements. Here’s an explanation of each Set type:
- HashSet
- LinkedHashSet
- TreeSet
HashSet
Set<E> set = new HashSet<>();
A HashSet is an unordered collection that stores unique elements using a hash table for storage. It does not maintain any specific order of elements and allows at most one null element
Best for: Fast operations and when order doesn’t matter
HashSet offers constant-time O(1) performance for basic operations (add, remove, contains) assuming a good hash function. It’s ideal when you need quick lookups and don’t care about element order.
Limitations: No guaranteed order of elements
The lack of ordering can be a drawback if you need to maintain any specific order of elements.
Main algorithms:
- add(E e): Adds an element to the set
- remove(Object o): Removes an element from the set
- contains(Object o): Checks if an element is in the set
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// add(): Add elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate, won't be added
System.out.println("HashSet: " + set);
// contains(): Check if an element exists
System.out.println("Contains 'Banana': " + set.contains("Banana"));
// remove(): Remove an element
set.remove("Cherry");
// size(): Get the number of elements
System.out.println("Size: " + set.size());
// Iterate through the set
System.out.println("Elements:");
for (String fruit : set) {
System.out.println(fruit);
}
// clear(): Remove all elements
set.clear();
System.out.println("Is empty: " + set.isEmpty());
}
}
LinkedHashSet
Set<E> set = new LinkedHashSet<>();
LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked list across all elements. It preserves the insertion order of elements during iteration while still providing the constant-time performance of HashSet for basic operations.
Best for: When insertion order matters and fast operations are needed
LinkedHashSet maintains insertion order while still providing near-constant time performance for basic operations. It’s ideal when you need to preserve the order of elements and have fast lookups.
Limitations: Slightly higher memory usage than HashSet
It uses more memory than HashSet due to the additional linked list structure.
Main algorithms:
- Similar to HashSet, with the addition of maintaining insertion order
import java.util.LinkedHashSet;
public class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>();
// add(): Add elements
set.add("Red");
set.add("Green");
set.add("Blue");
set.add("Red"); // Duplicate, won't be added
System.out.println("LinkedHashSet: " + set);
// contains(): Check if an element exists
System.out.println("Contains 'Green': " + set.contains("Green"));
// remove(): Remove an element
set.remove("Blue");
// size(): Get the number of elements
System.out.println("Size: " + set.size());
// Iterate through the set (maintains insertion order)
System.out.println("Elements:");
for (String color : set) {
System.out.println(color);
}
// clear(): Remove all elements
set.clear();
System.out.println("Is empty: " + set.isEmpty());
}
}
TreeSet
Set<E> set = new TreeSet<>();
TreeSet is an implementation of the SortedSet interface that uses a tree structure (specifically, a Red-Black tree) for storage. It stores unique elements in a sorted order, either using their natural ordering or a custom Comparator provided at set creation time.
Best for: When elements need to be sorted
TreeSet keeps elements sorted according to their natural order or a custom Comparator. It’s ideal when you need a sorted set of elements.
Limitations: Slower than HashSet and LinkedHashSet for basic operations
Basic operations (add, remove, contains) have O(log n) time complexity, making it slower than HashSet and LinkedHashSet for large sets.
Main algorithms:
- Similar to HashSet, but elements are automatically sorted
- first(): Returns the first (lowest) element
- last(): Returns the last (highest) element
For thread-safe operations, CopyOnWriteArraySet can be used, which is a thread-safe variant of Set.
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
// add(): Add elements
set.add(5);
set.add(2);
set.add(8);
set.add(1);
set.add(5); // Duplicate, won't be added
System.out.println("TreeSet: " + set);
// contains(): Check if an element exists
System.out.println("Contains 2: " + set.contains(2));
// remove(): Remove an element
set.remove(8);
// size(): Get the number of elements
System.out.println("Size: " + set.size());
// first(): Get the first (lowest) element
System.out.println("First element: " + set.first());
// last(): Get the last (highest) element
System.out.println("Last element: " + set.last());
// Iterate through the set (in sorted order)
System.out.println("Elements:");
for (Integer num : set) {
System.out.println(num);
}
// clear(): Remove all elements
set.clear();
System.out.println("Is empty: " + set.isEmpty());
}
}