- Understand Set and HashSet
- Learn uniqueness with Sets
- Master common collection operations
Sets and Common Collection Operations
Sets are collections that ensure uniqueness—no duplicate elements allowed. They're perfect when you need to track unique items or perform set operations like union and intersection.
What is a Set?
A Set is a collection that:
- Does NOT allow duplicate elements
- May or may not maintain order (depends on implementation)
- Provides efficient membership testing
Creating a HashSet
// Empty HashSet
HashSet<String> names = new HashSet<>();
// HashSet from another collection
List<String> list = Arrays.asList("A", "B", "C", "A");
HashSet<String> uniqueItems = new HashSet<>(list); // [A, B, C]
Common Set Operations
Adding Elements
HashSet<String> fruits = new HashSet<>();
boolean added1 = fruits.add("Apple"); // returns true
boolean added2 = fruits.add("Apple"); // returns false (duplicate)
Removing Elements
fruits.remove("Apple");
fruits.clear();
Checking Membership
boolean contains = fruits.contains("Apple");
Set Implementations
HashSet
- Fastest implementation
- No guaranteed order
- Best for most use cases
Set<String> hashSet = new HashSet<>();
TreeSet
- Maintains sorted order
- Slower than HashSet
- Elements must be comparable
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(3);
treeSet.add(1);
treeSet.add(2);
// Iteration order: 1, 2, 3
LinkedHashSet
- Maintains insertion order
- Slightly slower than HashSet
- Predictable iteration order
Set<String> linkedSet = new LinkedHashSet<>();
Set Operations
Union (All elements from both sets)
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5));
set1.addAll(set2); // set1 now contains: 1, 2, 3, 4, 5
Intersection (Common elements)
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> set2 = new HashSet<>(Arrays.asList(2, 3, 4));
set1.retainAll(set2); // set1 now contains: 2, 3
Difference (Elements in first set but not in second)
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> set2 = new HashSet<>(Arrays.asList(2, 3, 4));
set1.removeAll(set2); // set1 now contains: 1
When to Use Sets
Use Sets when you need:
- Unique elements only
- Fast membership testing
- Mathematical set operations
- To remove duplicates from a collection
Common use cases:
- Storing unique user IDs
- Tracking visited pages
- Removing duplicates from a list
- Implementing tags or categories
Sets give you automatic duplicate prevention, efficient contains() operations, and set-theory operations. Choose the implementation based on whether you need ordering (TreeSet), insertion order (LinkedHashSet), or raw speed (HashSet).
