Java Collections

Arrays have a fixed size and few operations. The Java Collections Framework provides growable, well-tested data structures behind a small set of interfaces: lists, sets, queues and maps. Choosing the right interface and implementation is one of the most consequential everyday decisions in Java code. This lesson maps the framework, shows the common operations, and gives rules for choosing. Collections are generic; see Generics for the type parameters used throughout.

The Framework at a Glance

The framework lives in java.util. Its interfaces define behavior; several classes implement each interface with different performance trade-offs. Code should declare variables with the interface and choose the implementation only where the object is created.

Core Interfaces

InterfaceContainsTypical implementations
ListOrdered elements, duplicates allowed, access by indexArrayList, LinkedList
SetUnique elementsHashSet, LinkedHashSet, TreeSet
Queue / DequeElements processed from the endsArrayDeque, PriorityQueue
MapKey–value pairs, unique keys (not a Collection)HashMap, LinkedHashMap, TreeMap

Choosing an Implementation

ClassOrderStrengthCost
ArrayListinsertionFast index access and iteration; the default listInserting or removing in the middle shifts elements
LinkedListinsertionCheap insert/remove at a known position via an iteratorSlow index access; more memory; rarely the best choice
HashSet / HashMapnoneConstant-time add, remove and lookup on averageNeeds correct equals and hashCode
LinkedHashSet / LinkedHashMapinsertionHash speed with predictable iterationA little more memory
TreeSet / TreeMapsortedSorted iteration, ranges, nearest-key queriesLogarithmic operations; elements must be comparable
ArrayDequeinsertionFast stack and queue at both endsNo null elements, no index access
PriorityQueueby priorityAlways removes the smallest (or highest-priority) elementIteration order is not sorted

The complexity behind these trade-offs is explained in the DSA lessons on arrays, hash tables and trees.

Lists, Sets and Maps in Use

// The three core interfaces: List (ordered), Set (unique), Map (key to value).
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

class CollectionsTour {
    public static void main(String[] args) {
        List<String> cart = new ArrayList<>(List.of("tea", "milk", "tea", "bread"));
        cart.add(1, "honey");                         // insert by position
        cart.removeIf(item -> item.equals("milk"));   // remove by condition
        System.out.println("list: " + cart + ", second = " + cart.get(1));

        Set<String> unique = new LinkedHashSet<>(cart);  // duplicates dropped, insertion order kept
        Set<String> sorted = new TreeSet<>(cart);        // duplicates dropped, natural order
        System.out.println("linked set: " + unique + ", tree set: " + sorted);

        Map<String, Double> prices = new HashMap<>();
        prices.put("tea", 4.5);
        prices.put("bread", 2.0);
        prices.putIfAbsent("tea", 9.9);                  // ignored: key already present
        System.out.println("tea = " + prices.get("tea")
                + ", coffee = " + prices.getOrDefault("coffee", 0.0));

        List<String> fixed = List.of("a", "b");          // immutable
        try {
            fixed.add("c");
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of is immutable");
        }
    }
}

Output:

list: [tea, honey, tea, bread], second = honey
linked set: [tea, honey, bread], tree set: [bread, honey, tea]
tea = 4.5, coffee = 0.0
List.of is immutable

Immutable Collections

The factories List.of, Set.of and Map.of (Java 9+) create compact, unmodifiable collections; any attempt to change them throws UnsupportedOperationException, and they reject null elements. List.copyOf makes an unmodifiable copy of an existing collection. Return immutable collections from methods whenever callers should not change them; it removes a whole class of bugs.

Working with Maps

Modern Map methods replace most hand-written “check, then put” code: getOrDefault, putIfAbsent, computeIfAbsent (ideal for maps of lists) and merge (ideal for counters). A TreeMap keeps its keys sorted, which makes the word count below print in alphabetical order.

// Count words with Map.merge, then report them sorted by count.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

class WordFrequency {
    public static void main(String[] args) {
        String text = "the cat and the hat and the bat";
        Map<String, Integer> counts = new TreeMap<>();     // keys kept in alphabetical order
        for (String word : text.split(" ")) {
            counts.merge(word, 1, Integer::sum);           // insert 1, or add 1 to the existing count
        }
        System.out.println(counts);

        List<Map.Entry<String, Integer>> byCount = new ArrayList<>(counts.entrySet());
        byCount.sort(Map.Entry.<String, Integer>comparingByValue().reversed());
        System.out.println("most frequent: " + byCount.get(0).getKey());
    }
}

Output:

{and=2, bat=1, cat=1, hat=1, the=3}
most frequent: the

Queues, Stacks and Sequences

Stacks, Queues and Priorities

ArrayDeque is the recommended stack and queue — prefer it to the legacy Stack and Vector classes, which synchronize every call. A PriorityQueue always hands out its smallest element first, according to natural order or a Comparator.

Sequenced Collections

Java 21 added sequenced collections: List, Deque, LinkedHashSet and LinkedHashMap now share getFirst, getLast, addFirst, addLast and reversed.

// Deque as stack and queue, PriorityQueue, and Java 21 sequenced collections.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

class QueuesAndSequences {
    public static void main(String[] args) {
        Deque<String> stack = new ArrayDeque<>();
        stack.push("a"); stack.push("b"); stack.push("c");
        System.out.println("stack pop: " + stack.pop());       // c: last in, first out

        Queue<String> queue = new ArrayDeque<>(List.of("first", "second"));
        queue.offer("third");
        System.out.println("queue poll: " + queue.poll());     // first: first in, first out

        Queue<Integer> tasks = new PriorityQueue<>(List.of(5, 1, 4, 2));
        StringBuilder order = new StringBuilder();
        while (!tasks.isEmpty()) order.append(tasks.poll()).append(' ');
        System.out.println("priority order: " + order.toString().trim());

        List<String> steps = new ArrayList<>(List.of("wake", "code", "sleep"));
        System.out.println(steps.getFirst() + " .. " + steps.getLast());   // Java 21
        System.out.println("reversed view: " + steps.reversed());
    }
}

Output:

stack pop: c
queue poll: first
priority order: 1 2 4 5
wake .. sleep
reversed view: [sleep, code, wake]

Common Pitfalls

Mistakes to Avoid

  • Modifying while iterating: calling list.remove inside a for-each loop throws ConcurrentModificationException. Use removeIf or an explicit Iterator.
  • Mutable keys: changing a field that hashCode depends on after inserting the object into a HashSet or HashMap makes it unfindable.
  • Arrays.asList returns a fixed-size view of the array: set works, add and remove throw.
  • Thread safety: the standard implementations are not synchronized. Use java.util.concurrent classes such as ConcurrentHashMap when several threads share a collection.

Practice

Exercises

  1. Build a Map<String, List<String>> that groups words by their first letter, using computeIfAbsent.
  2. Use a TreeMap's floorKey to find the tax band for an income from a map of band thresholds.
  3. Simulate a print queue where urgent jobs go first, using a PriorityQueue with a Comparator. The runnable lab demos 37 to 42 show more collection programs.