Memra

Set & Map

HashSet/TreeSet/LinkedHashSet, HashMap/TreeMap, key uniqueness, and a word-count built with a HashMap.

Set: a collection with no duplicates

A Set<E> stores at most one of each element; add returns false (and does nothing) if the element is already present. Three implementations differ only in iteration order and performance:

- HashSet — O(1) add/contains, no order guarantee. The default. - LinkedHashSet — O(1), iterates in insertion order. - TreeSet — O(log n), iterates in sorted order (natural ordering or a supplied Comparator); implements NavigableSet (first, last, ceiling, floor).

Map: key → value associations

A Map<K,V> maps unique keys to values. The implementations mirror the sets:

- HashMap — O(1) get/put, no order, allows one null key. - LinkedHashMap — insertion (or access) order. - TreeMap — keys kept sorted, O(log n).

Core operations: put(k, v) (returns the previous value or null), get(k) (returns null if absent), containsKey(k), getOrDefault(k, def), and remove(k).

Worked example — word count. Counting occurrences with a HashMap<String,Integer> is the canonical Map idiom. getOrDefault reads the current count (0 if the word is new), adds one, and put writes it back:

String[] text = { "to", "be", "or", "not", "to", "be" };
Map<String,Integer> counts = new HashMap<>();
for (String w : text)
    counts.put(w, counts.getOrDefault(w, 0) + 1);
System.out.println(counts.get("to") + " " + counts.get("be"));
// 2 2

An equivalent one-liner is counts.merge(w, 1, Integer::sum), which inserts 1 if absent or sums otherwise. To iterate the result, loop counts.entrySet() and read entry.getKey() / entry.getValue(). Swapping HashMap for TreeMap would make that iteration come out alphabetically sorted by key — same code, ordered output.

NORMAL ~/memra/learn/comp-308/set-and-map utf-8 LF