Java Collections: Set and Map
Set is a collection that stores unique elements with no duplicates, commonly implemented as HashSet (unordered) or TreeSet (sorted). Map stores key-value pairs, commonly implemented as HashMap or TreeMap.
HashMap provides fast average O(1) lookups by key, while TreeMap keeps keys sorted at the cost of O(log n) operations.
Set<Type> s = new HashSet<>();
Map<K,V> m = new HashMap<>();
m.put(key, value);Using Set
HashSet automatically rejects duplicate values when you call add(). It does not guarantee any particular ordering of elements.
Using Map
Map.put(key, value) stores an entry, get(key) retrieves it, and containsKey() checks for existence. Keys must be unique; values can repeat.
import java.util.HashSet;
import java.util.HashMap;
import java.util.Set;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Set<String> names = new HashSet<>();
names.add("Amy");
names.add("Amy");
System.out.println(names.size());
Map<String, Integer> ages = new HashMap<>();
ages.put("Amy", 25);
System.out.println(ages.get("Amy"));
}
}1
25HashSet rejects the duplicate "Amy", and HashMap stores and retrieves a value by key.
Key points
- Set stores only unique elements.
- Map stores key-value pairs with unique keys.
- HashMap and HashSet offer fast average-case operations.
- TreeMap and TreeSet keep entries sorted.
