JavaCollectionsintermediate
Updated:

Java Collections Framework: The Complete Map

6 min read

One mental map of the entire Collections Framework: the interface hierarchy, the workhorse implementations, complexity trade-offs, and the rules for picking the right one.

TL;DR – Quick Answer

The Java Collections Framework is a unified set of interfaces and classes in java.util for storing and processing groups of objects. Its core interfaces are List (ordered, duplicates allowed), Set (no duplicates), Queue (processing order), and Map (key-value pairs, a separate hierarchy). Workhorse implementations include ArrayList, HashSet, ArrayDeque, and HashMap.

On This Page

If Java interviews had a syllabus, collections would be printed in bold on page one. Between "difference between ArrayList and LinkedList" and "how does HashMap work internally," a third of a typical fresher interview lives inside java.util. But candidates who memorize twenty isolated comparisons still get lost, because they never built the map — the hierarchy that makes every comparison obvious.

This guide is that map. Individual deep dives (List, Set, Map) branch off from here.

Why the framework exists

Before Java 1.2, you had arrays, Vector, and Hashtable — each with its own method names and no common type. The Collections Framework unified all of this around a small set of interfaces so that:

  • Code targets interfaces, not classes. List<String> names = new ArrayList<>(); means you can switch to LinkedList by editing one word.
  • Algorithms are written once. Collections.sort() works on every List ever written, including yours.
  • Behavior is predictable. Anything called a Set rejects duplicates; anything called a List preserves insertion order and positions.

That first bullet is runtime polymorphism doing real work — the framework is the biggest everyday example of programming to an abstraction.

The hierarchy: one diagram to memorize

Iterable
   └── Collection
         ├── List   → ArrayList, LinkedList, Vector (legacy)
         ├── Set    → HashSet, LinkedHashSet
         │     └── SortedSet → NavigableSet → TreeSet
         └── Queue  → PriorityQueue, LinkedList
               └── Deque → ArrayDeque, LinkedList

Map (separate hierarchy!)
   ├── HashMap → LinkedHashMap
   ├── SortedMap → NavigableMap → TreeMap
   └── Hashtable (legacy)

Three facts about this diagram settle a shocking number of interview questions:

  1. Map does not extend Collection. A key-value pair does not fit add(E element), so Map has its own hierarchy with put(K, V).
  2. LinkedList appears twice. It implements both List and Deque, so it can act as a list, queue, or stack.
  3. Iterable is the root, and it is what the for-each loop requires — that is why for (String s : anyCollection) always works.

List: ordered, indexed, duplicates welcome

A List remembers insertion order and gives every element an index. Use it when position matters or duplicates are legitimate data.

Implementation Backing structure Strength Weakness
ArrayList Resizable array O(1) index access O(n) inserts in the middle
LinkedList Doubly-linked nodes O(1) add/remove at ends O(n) index access
Vector Synchronized array Legacy thread safety Slow; avoid in new code

Default to ArrayList; the cases where LinkedList genuinely wins are rarer than most tutorials suggest, because index access and cache-friendly memory layout dominate real workloads.

Set: uniqueness enforced for you

A Set silently refuses duplicates — add() returns false instead of throwing. Choose the implementation by the iteration order you need:

  • HashSet — no order guarantee, fastest (average O(1) add/contains).
  • LinkedHashSet — iterates in insertion order, slightly heavier.
  • TreeSet — iterates sorted, O(log n) operations, elements must be comparable.

Uniqueness for HashSet depends on the equals() and hashCode() methods of your objects — override one without the other and duplicates will slip through.

Queue and Deque: processing order

Queue models elements waiting for processing (usually FIFO); Deque allows work at both ends, which also makes it Java's recommended stack.

  • ArrayDeque — the default choice for both stack and queue roles.
  • PriorityQueue — always hands you the smallest element next, not the oldest.
  • Avoid the legacy Stack class; ArrayDeque is faster and the JavaDoc itself recommends it.

Map: the key-value workhorse

Map stores unique keys pointing to values. It powers caches, counters, lookups, and probably half the Java code in production anywhere.

Implementation Ordering Null keys Typical use
HashMap None One allowed General lookups
LinkedHashMap Insertion (or access) order One allowed Predictable iteration, LRU caches
TreeMap Sorted by key Not allowed Range queries, sorted views
Hashtable None Not allowed Legacy; avoid

HashMap is the single most-asked collection in interviews — first its everyday operations, then its internal working: buckets, hashing, and the Java 8 switch from linked lists to red-black trees in crowded buckets.

The framework in action

Here is one program touching all four families — run it and study the output ordering:

import java.util.*;

public class FrameworkTour {
    public static void main(String[] args) {
        List<String> tasks = new ArrayList<>(
            List.of("build", "test", "build", "deploy"));
        System.out.println("List keeps duplicates: " + tasks);

        Set<String> unique = new HashSet<>(tasks);
        System.out.println("Set removed one: " + unique);

        Set<String> sorted = new TreeSet<>(tasks);
        System.out.println("TreeSet sorts: " + sorted);

        Deque<String> stack = new ArrayDeque<>();
        stack.push("first");
        stack.push("second");
        System.out.println("Stack pops: " + stack.pop());  // second

        Map<String, Integer> freq = new HashMap<>();
        for (String t : tasks) {
            freq.merge(t, 1, Integer::sum);   // count occurrences
        }
        System.out.println("Word counts: " + freq);
    }
}

What to notice: the same data behaves differently in each structure — the Set drops the duplicate "build", the TreeSet alphabetizes, and merge() builds a frequency counter in one line, a pattern worth memorizing for coding rounds.

Pro tip: Declare variables by interface (List, Set, Map, Deque) and construct by class (new ArrayList<>()). Interviewers scan for this habit in your code; production reviewers reject PRs that lack it.

Sorting custom objects is the second must-know pattern:

import java.util.*;

record Course(String name, int hours) { }

public class SortDemo {
    public static void main(String[] args) {
        List<Course> courses = new ArrayList<>(List.of(
            new Course("Java", 120),
            new Course("SQL", 40),
            new Course("Spring Boot", 80)));

        courses.sort(Comparator.comparingInt(Course::hours));
        System.out.println(courses);   // sorted by hours ascending

        courses.sort(Comparator.comparing(Course::name).reversed());
        System.out.println(courses);   // by name, Z to A
    }
}

What to notice: Comparator.comparing with a method reference replaces the anonymous-class boilerplate older tutorials still teach. Chaining .reversed() or .thenComparing(...) composes multi-level sorts cleanly — the same functional style you will meet again in Java 8 streams.

Choosing a collection: the 10-second flowchart

  1. Key → value lookups? Use a Map. Sorted keys → TreeMap; insertion order → LinkedHashMap; otherwise HashMap.
  2. Duplicates must be impossible? Use a Set. Same ordering logic picks Hash/Linked/Tree.
  3. Positional access or duplicates are data? Use a ListArrayList unless you are constantly adding/removing at both ends.
  4. Elements processed in a specific order? ArrayDeque for FIFO/LIFO, PriorityQueue for "smallest first."

Common mistake: A common mistake beginners make is choosing by memorized Big-O alone — picking LinkedList "because insertion is O(1)." That O(1) applies only when you already hold the node position; reaching the middle first costs O(n), and ArrayList beats it in practice for almost every workload thanks to CPU cache behavior. Choose by the operations your code actually performs.

Three cross-cutting facts interviewers probe

Fail-fast iteration. Modifying an ArrayList or HashMap while for-each looping over it throws ConcurrentModificationException. Remove during iteration with Iterator.remove() or removeIf() instead.

Generics and autoboxing. Collections hold objects only — List<int> will not compile; List<Integer> boxes each value. Generics give compile-time type safety and erase to raw types at runtime.

Thread safety. The main implementations are not synchronized. For concurrent access, reach for ConcurrentHashMap or CopyOnWriteArrayList rather than wrapping with Collections.synchronizedList() — the concurrent classes lock far more selectively and scale much better.

Interview note: "Which collection would you use for X and why?" is the most common collections opener at Hyderabad companies. Answer with the flowchart logic above — requirement, then interface, then implementation, then one-line justification. Practice the full question bank on our Java collections interview questions page.

Where to go from here

You now have the map; the marks are in the details. Work through the List, Set, and Map interface guides linked above next, then finish with HashMap internals — the question that separates shortlists from rejections. We build these into live coding drills during the collections week of the Java Full Stack course.

Frequently Asked Questions

What is the Java Collections Framework?
It is the standard architecture in java.util for representing and manipulating groups of objects. It defines interfaces like List, Set, Queue, and Map, ready-made implementations like ArrayList and HashMap, and utility algorithms in the Collections class. Because everything shares common interfaces, you can swap implementations with a one-line change.
Is Map part of the Collection interface?
No. Map is part of the Collections Framework but does not extend the Collection interface, because a key-value pair does not fit the single-element contract methods like add(E). Map sits in its own hierarchy, though its keySet(), values(), and entrySet() views bridge back into Collection types.
What is the difference between Collection and Collections in Java?
Collection (singular) is the root interface that List, Set, and Queue extend. Collections (plural) is a utility class full of static helper methods such as sort(), reverse(), unmodifiableList(), and synchronizedList(). Mixing these up is one of the fastest ways to fail a screening round.
Which collection should I use most often?
For day-to-day work: ArrayList for ordered data, HashMap for key-value lookups, HashSet for uniqueness checks, and ArrayDeque for stack or queue behavior. These four cover the vast majority of real code. Switch to Tree or Linked variants only when you specifically need sorted order or insertion-order iteration.
Why do collections only store objects and not primitives like int?
Generics work only with reference types, so a collection cannot hold a bare int. Java autoboxes primitives into wrapper objects: List<Integer> stores Integer objects, and boxing happens automatically when you add an int. This costs some memory and CPU, which is why performance-critical code sometimes sticks with arrays.
What is a fail-fast iterator?
An iterator that throws ConcurrentModificationException if the collection is structurally modified after the iterator was created, except through the iterator's own remove() method. ArrayList and HashMap iterators are fail-fast. It is a bug-detection mechanism, not a thread-safety guarantee - use concurrent collections for real multi-threaded access.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 14 July 2026 LinkedIn
Chat with us