Sets and Maps — cheat sheet
From: fundamentals/14-sets-and-maps.md.
Set
- Like a
List, but: no defined order (no indexing/.get(i)), and every element is unique — adding a duplicate is a silent no-op, not an error. - Mutable (
new HashSet<>()) or immutable (Set.of(...), throws on mutation attempts), same split asList/ArrayList. - Checking whether an element is contained (
contains) is significantly faster than in aList, especially at scale — this is usually the reason to reach for aSetinstead of aList.
Map
- Stores key/value pairs (
Map<K, V>). LikeList/Set, can't hold primitives directly, and has no defined order. - Keys are unique (like
Setelements); values may repeat. put(key, value)— inserts, or overwrites if the key already exists.get(key)— retrieves the value for a key.remove(key)— removes an entry; removing a non-existent key is a silent no-op.keySet()— iterate over keys (commonly paired withgetinside the loop).- Mutable (
new HashMap<>(...)) or immutable (Map.of(...), throws on mutation attempts). - Alternate terminology: Map = "Dictionary";
HashMap= a concrete "Hash Table" implementation. Checking whether a key exists is very fast, same underlying mechanism asSet.
When to reach for Set/Map over List
- Set over List: you only care about membership/uniqueness, not order or duplicates, and especially when checking "is X already in here?" happens often on a large collection.
- Map over List: you need to look values up by some key (not by position), e.g. "the exam score for this student," "the capital city of this country."