Set & HashSet in Java
Work with unique collections using HashSet, LinkedHashSet, and TreeSet, understand set operations like union, intersection, and difference.
Set Basics
1. Creating an Empty Set
A `HashSet` stores unique elements with no guaranteed order. Duplicate values are silently ignored.
2. Creating a Set with Initial Values
Pass a list to the `HashSet` constructor, or use `Set.of()` for an immutable set. Duplicates are dropped automatically.
Basic Set Operations
1. Adding Values to a Set
`add()` inserts a value and returns `true` if it was added, `false` if it was already present.
2. Checking if a Value Exists
`contains()` returns `true` if the value is in the set.
3. Removing a Value
`remove()` deletes the value and returns `true` if it existed, `false` if not found.
4. Clearing the Set
`clear()` removes all elements. The set object still exists.
5. Getting Set Size
`size()` returns the number of unique elements. `isEmpty()` returns true if the set has no elements.
Traversing a Set
1. Traversing using for-each
Use an enhanced for-each loop to iterate all elements. Order is not guaranteed with `HashSet`.
2. Traversing using forEach (lambda)
`forEach` with a lambda is the most concise way to iterate.
Converting Set
1. Converting Set to List
Wrap with `new ArrayList<>()` to convert a set to an indexed list.
2. Converting List to Set (Remove Duplicates)
Wrapping a `List` in a `HashSet` is the idiomatic way to deduplicate elements.
Set Operations
1. Union of Two Sets
Union = all elements from both sets. Use `addAll()` on a copy of one set.
2. Intersection of Two Sets
Intersection = only elements present in both sets. Use `retainAll()` on a copy.
3. Difference of Two Sets
Difference = elements in A but not in B. Use `removeAll()` on a copy of A.
Set Variants
1. LinkedHashSet (Insertion Order)
`LinkedHashSet` preserves the order elements were inserted — unlike `HashSet` which has no guaranteed order.
2. TreeSet (Sorted Order)
`TreeSet` keeps elements sorted in natural (alphabetical / numerical) order.
Set Fundamentals Using Map
A Set can be conceptually represented using a Map where values are stored as keys and the map values are ignored. This explains why Set supports fast existence checks.
1. Simulating a Set Using Map
Store values as map keys — the map value is irrelevant (use a placeholder like `true`).
2. Why Set Exists if Map Can Do This?
Set is a cleaner, purpose-built abstraction over the same hash-based structure.