A2Z Lesson

Log in
← Back to the A2Z sheet

Step 01 Beginner Problems — Standard Libraries & Collections

Java Collections

Medium

The Java Collections Framework is Java's answer to the STL: a unified family of interfaces — List, Set, Queue, Map — with implementations whose names tell you their trade-offs (ArrayList, HashMap, TreeSet, PriorityQueue...). Fluency here is what makes Java solutions as short as C++ ones. This lesson maps the framework, gives the frequency-counting pattern you will reuse constantly, and lists the traps specific to Java.

The framework map

Four interface families cover nearly everything:

List — ordered, duplicates allowed: ArrayList (your default), LinkedList. Set — unique elements: HashSet (fast, unordered), TreeSet (sorted), LinkedHashSet (insertion order). Queue / Deque — FIFO processing and double-ended work: ArrayDeque, PriorityQueue (a heap). Map — key-value pairs, technically outside Collection but used identically: HashMap (fast), TreeMap (sorted keys), LinkedHashMap (insertion order).

The naming code: 'Hash' = hash table, average O(1), no order; 'Tree' = balanced tree, O(log n), sorted; 'Array' = backed by a resizable array; 'Linked' = node chain. Once you can decode names, you can guess any class's behaviour before reading its docs.

ArrayList vs LinkedList — the one real List decision

ArrayList stores elements in a growable array: get(i) is O(1), add at the end is amortised O(1), but inserting or deleting in the middle shifts everything — O(n). LinkedList stores nodes with next/previous links: insertion at a known node is O(1), but reaching that node (get(i)) is O(n).

Verdict for DSA: ArrayList almost always. LinkedList wins only when you repeatedly insert/remove at the head or via an iterator you already hold — and even then ArrayDeque usually beats it for queue work. Declaring variables as the interface (List<Integer> list = new ArrayList<>();) lets you swap implementations with a one-word change.

HashMap and the frequency pattern

HashMap<K,V> gives average O(1) put/get/containsKey. The single most-used pattern in this sheet is frequency counting, and Java's getOrDefault (or merge) makes it a one-liner inside the loop. Keys must implement equals and hashCode properly — built-in types (Integer, String, Character) already do; your own classes must override both, consistently.

Map<Integer, Integer> freq = new HashMap<>(); for (int x : nums) { freq.put(x, freq.getOrDefault(x, 0) + 1); } int best = nums[0]; for (Map.Entry<Integer, Integer> e : freq.entrySet()) { if (e.getValue() > freq.get(best)) { best = e.getKey(); } } System.out.println(best); // highest occurring element

PriorityQueue, Deque and the Collections toolbox

PriorityQueue is a min-heap by default — peek/poll give the smallest; pass Comparator.reverseOrder() for a max-heap. Poll and offer cost O(log n), peek is O(1). Top-K problems: keep a heap of size K and evict the smallest as you go.

Use ArrayDeque for stacks and queues (push/pop/peek for stack behaviour, offer/poll for queues) — the legacy Stack class is synchronised and slow, and LinkedList-as-queue is rarely better.

The static Collections class supplies the algorithms: sort (O(n log n), stable), reverse, frequency(collection, x), max, min, binarySearch (sorted lists only), and shuffle. Arrays.sort does the same for raw arrays — and for int[] it is a fast dual-pivot quicksort, while object arrays get a stable TimSort.

Complexities and Java-specific traps

Text summary: ArrayList get O(1) | add-end O(1) amortised | insert/delete middle O(n) HashMap/HashSet average O(1) | TreeMap/TreeSet O(log n), sorted PriorityQueue peek O(1) | offer/poll O(log n)

Traps: (1) Autoboxing — collections hold Integer, not int; unboxing a null value throws NullPointerException, a classic when a map key is absent. (2) == compares references on objects; use .equals for values — two Integer objects with the same value can fail == outside the small cache range. (3) Removing elements from a list while iterating by index skips elements; use an Iterator or iterate backwards. (4) HashMap order is unspecified — if a test expects sorted output, use TreeMap or sort explicitly.

Key points

  • Decode class names: Hash = average O(1), unordered; Tree = O(log n), sorted; Array = array-backed; Linked = node chain.
  • ArrayList is the default List (O(1) get); LinkedList rarely wins in DSA — prefer ArrayDeque for queue/stack work.
  • Frequency counting: freq.put(x, freq.getOrDefault(x, 0) + 1) — the pattern behind a dozen problems.
  • PriorityQueue is a min-heap by default; reverseOrder() makes it a max-heap; top-K = heap of size K.
  • Use .equals, never ==, for object values; guard against null unboxing from absent map keys.
  • Collections.sort/frequency/max/binarySearch and Arrays.sort cover the standard algorithm needs.

Suggested questions

Highest Occurring Element in an Array ↗ The getOrDefault frequency pattern from this lesson, graded.
Second Highest Occurring Element ↗ One pass over the frequency map tracking the top two values.
Valid Anagram ↗ Two frequency maps, or one map incremented and decremented — try both.
Basic Hashing The concept lesson: why hash tables average O(1) and when they do not.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.