Notifications

No notifications

/Phase 3

Collections β€” List, Set, Map

The Java Collections Framework gives you ready-made data structures: List (ordered, duplicates), Set (unique), Map (keyβ†’value). You always code to the *interface* and pick the *implementation* based on performance trade-offs (ArrayList vs LinkedList, HashMap vs TreeMap, …).

On this page

Detailed Theory

# Collections Framework

The hierarchy

Collection
β”œβ”€β”€ List      ordered, duplicates allowed     β†’ ArrayList, LinkedList
β”œβ”€β”€ Set       unique elements                  β†’ HashSet, LinkedHashSet, TreeSet
└── Queue     FIFO / priority                  β†’ ArrayDeque, PriorityQueue

Map (NOT a Collection) key β†’ value β†’ HashMap, LinkedHashMap, TreeMap

Always code to the interface

List<String> names = new ArrayList<>();   // good
Map<String,Integer> ages = new HashMap<>();
The diamond <> lets the compiler infer the type arguments (Java 7+).

ArrayList vs LinkedList

opArrayListLinkedList
get(i)O(1)O(n)
add at endamortised O(1)O(1)
insert middleO(n)O(1) (with iterator)
memorylowhigh (node per element)

Use ArrayList by default. LinkedList is rarely the right answer.

HashSet vs LinkedHashSet vs TreeSet

  • HashSet β€” unordered, O(1) add/contains
  • LinkedHashSet β€” *insertion* order preserved
  • TreeSet β€” sorted (natural or by Comparator), O(log n)

HashMap vs LinkedHashMap vs TreeMap

Same trade-offs as the Set variants β€” HashMap is the default.

Iteration

for (String s : names) System.out.println(s);

for (var e : ages.entrySet()) System.out.println(e.getKey() + " = " + e.getValue());

names.forEach(System.out::println); // Java 8+

Immutable factories (Java 9+)

List<Integer>     a = List.of(1, 2, 3);
Set<String>       b = Set.of("x", "y");
Map<String,Integer> c = Map.of("a", 1, "b", 2);
These throw UnsupportedOperationException on add/put.

Collections utility class

Collections.sort(list);                 // natural order, in place
Collections.sort(list, Comparator.reverseOrder());
Collections.reverse(list);
Collections.shuffle(list);
int min = Collections.min(list);
int max = Collections.max(list);

Common map idioms

// frequency count
Map<String,Integer> freq = new HashMap<>();
for (String w : words) freq.merge(w, 1, Integer::sum);

// default if missing int v = freq.getOrDefault("xyz", 0);

// compute if absent Map<String,List<Integer>> groups = new HashMap<>(); groups.computeIfAbsent("evens", k -> new ArrayList<>()).add(2);