Lesson 29 / 38

Collections

Pick the right data structure from the List, Set and Map families, use generics for type safety, and reach for map helpers like merge and computeIfAbsent.

The three families

List — ordered, duplicates allowed (ArrayList, LinkedList). Set — no duplicates (HashSet, TreeSet, LinkedHashSet). Map — key → value (HashMap, TreeMap, LinkedHashMap). Program to the interface, not the implementation.

Everyday usage

Generics (<String>) give compile-time type safety. Iterate with for-each; use getOrDefault, computeIfAbsent, merge on maps to avoid null checks.

Map<String, Integer> counts = new HashMap<>();
for (String w : words) {
    counts.merge(w, 1, Integer::sum);
}
List<String> names = new ArrayList<>(List.of("Ada", "Al"));
names.forEach(System.out::println);

Pick the collection

Quick check: You need to store unique user IDs and check membership quickly. Which type?

  • ArrayList
  • HashSet
  • LinkedList
  • int[]
Answer

HashSet — HashSet gives O(1) average contains() and rejects duplicates automatically.