Collections Framework in Java: Interfaces, Implementations, and Examples

Learn how List, Set, Map, and Deque fit together, then choose implementations confidently through one consistent Java example.

KnowledgeGate Team

Exam prep & CS education

Updated 2 Nov 20265 min read
Collections Framework in Java: Interfaces, Implementations, and Examples

List, ArrayList, Set, HashSet, Map, and HashMap can look unrelated. Separate interfaces, implementations, and algorithms, and the pattern becomes clear. The framework's interfaces, implementations, and algorithms fit together in one consistent program.

What the Java Collections Framework actually gives you

The framework has three parts. Interfaces describe behaviour, implementations store data, and algorithms perform common operations. In List<String> names = new ArrayList<>();, callers use the List contract while ArrayList supplies storage.

Collection is the main interface for groups of elements. List, Set, and Queue extend it. Map stores key-value pairs and is not a Collection subtype. Iterable explains why enhanced for can traverse collections.

For related Java and programming study, browse Coding & Skill Development Courses.

Java collections hierarchy shows Collection branching to List, Set, Queue, and Deque, with Map separate; examples include ArrayList values and LinkedHashMap scores.

Choose the interface from the behaviour you need

Requirement

Interface

Starting implementation

Reason

Ordered values, duplicates, index access

List

ArrayList

Retains position and permits repeated values

Unique values in first-seen order

Set

LinkedHashSet

Rejects duplicates and retains insertion order

FIFO processing

Deque

ArrayDeque

Efficient operations at both ends

Key-value lookup in insertion order

Map

LinkedHashMap

Associates each key with a value and retains insertion order

Automatically sorted unique values or keys

SortedSet or SortedMap

TreeSet or TreeMap

Maintains sorted order

List defines the available operations. ArrayList defines how this instance stores and accesses elements. With List<String> ticketIds = new ArrayList<>();, the implementation can change without rewriting callers that need only List behaviour.

For "find the priority for a ticket ID", List<Integer> loses the relationship. Map<String, Integer> represents it directly.

Know the tradeoffs of common implementations

ArrayList provides constant-time indexed reads and amortised constant-time append. Middle insertions or removals may shift elements. LinkedList has linear indexed access, so consider it when its end operations or node-based behaviour match the job. For stacks or queues, start with ArrayDeque.

HashSet and HashMap make no iteration-order guarantee. Their linked variants retain insertion order. TreeSet and TreeMap keep data sorted with logarithmic operations. Hash lookup is expected constant time on average, but it is not sorted and cannot promise printed order.

At the interface-selection level, treat a map as key-value lookup with an order policy. HashMap Internals in Java: Buckets, Collisions, Resizing and Treeification takes the next layer: bucket selection, collision handling, resizing, and treeification.

Worked example: ticket arrivals, priority updates, and an urgent queue

Flow from ticket scans to unique IDs, final priorities, sorted values, and FIFO urgent queue.

Ticket scans arrive as T-104, T-208, T-315, T-104, T-422. T-104's priority changes from 2 to 5; T-208 is 4, T-315 is 1, and T-422 is 3. Priorities of 4 or 5 enter a FIFO urgent queue.

java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CollectionsOverview {
    public static void main(String[] args) {
        List<String> arrivals = new ArrayList<>(
                Arrays.asList("T-104", "T-208", "T-315", "T-104", "T-422"));
        Set<String> ticketIds = new LinkedHashSet<>(arrivals);

        Map<String, Integer> priorities = new LinkedHashMap<>();
        priorities.put("T-104", 2);
        priorities.put("T-208", 4);
        priorities.put("T-315", 1);
        priorities.put("T-104", 5);
        priorities.put("T-422", 3);

        Deque<String> urgentQueue = new ArrayDeque<>();
        for (Map.Entry<String, Integer> entry : priorities.entrySet()) {
            if (entry.getValue() >= 4) {
                urgentQueue.addLast(entry.getKey());
            }
        }

        List<Integer> sortedPriorities = new ArrayList<>(priorities.values());
        Collections.sort(sortedPriorities);

        System.out.println("Arrivals: " + arrivals);
        System.out.println("Unique tickets: " + ticketIds);
        System.out.println("Final priorities: " + priorities);
        System.out.println("Sorted priorities: " + sortedPriorities);
        System.out.println("Next urgent: " + urgentQueue.removeFirst());
        System.out.println("Queue now: " + urgentQueue);
    }
}

Output:

Code
Arrivals: [T-104, T-208, T-315, T-104, T-422]
Unique tickets: [T-104, T-208, T-315, T-422]
Final priorities: {T-104=5, T-208=4, T-315=1, T-422=3}
Sorted priorities: [1, 3, 4, 5]
Next urgent: T-104
Queue now: [T-208]

The list keeps all five scans, including duplicate T-104. The linked set keeps four first-seen ticket IDs. The second put("T-104", 5) replaces the value but preserves T-104's position. Sorting produces 1, 3, 4, 5. T-104 and T-208 have priorities of at least 4, so FIFO removal returns T-104 and leaves T-208.

Traverse, update, and sort without mixing up APIs

Use enhanced for to read arrivals, and priorities.entrySet() when both key and value are needed. keySet() exposes keys, while values() exposes values.

Use an Iterator when removing during traversal:

java
List<Integer> values = new ArrayList<>(Arrays.asList(2, 5, 8, 11));
Iterator<Integer> iterator = values.iterator();
while (iterator.hasNext()) {
    if (iterator.next() % 2 != 0) {
        iterator.remove();
    }
}
// values is [2, 8]

Calling values.remove(value) inside enhanced for can cause ConcurrentModificationException. Collections.sort(sortedPriorities) changes the copy [5, 4, 1, 3] into [1, 3, 4, 5]. A map values view cannot be sorted in place. Use a Comparator when natural order is not enough. Java Iterators and Comparators: Runnable Examples, Sorting Rules and Common Traps develops cursor state, multi-key comparator chains, and comparison-based uniqueness in TreeSet.

Common errors and what to do instead

Mistake

What goes wrong

Fix

new List<>()

An interface cannot be instantiated

Use new ArrayList<>()

List<int>

Generics require reference types

Use List<Integer>

Add to Arrays.asList("A", "B")

The returned list has fixed size

Wrap it in new ArrayList<>(...)

removeFirst() on an empty deque

It throws an exception

Check emptiness, or use pollFirst() if null is acceptable

For custom keys and set elements, equals() and hashCode() must agree. Otherwise, equal Ticket objects may appear duplicated or miss a lookup. For strings, .equals() checks content, while == checks whether references point to the same object. Immutability does not change that distinction.

How interviews and objective assessments test collections

Typical questions ask you to select an interface, predict output after add, put, or queue operations, detect an order assumption, or compare time complexity.

Check each result:

  1. Deduplicate [4, 2, 4, 1, 2] while keeping first-seen order. new LinkedHashSet<>(values) gives [4, 2, 1].

  2. Put ("x", 1) and then ("x", 3) into a map. Its size is 1, and the value for x is 3.

  3. Run addLast("red"), addLast("blue"), then removeFirst(). It returns red and leaves [blue].

  4. Remove odd values from [2, 5, 8, 11] through an iterator. The result is [2, 8].

For "unique job IDs, always printed smallest first", you need uniqueness and sorted order. Choose SortedSet<Integer> with TreeSet<Integer>, not HashSet<Integer>.

The short version and the next step

Ask five questions before choosing a collection:

  1. Do duplicates matter?

  2. Does encounter order matter?

  3. Must values remain sorted?

  4. Is access by position, key, or processing order?

  5. Will the code mostly read, append, search, or remove?

Translate the answers into List, Set, SortedSet, Map, or Deque before naming an implementation. Here, the list kept five scans, the linked set four ticket IDs, the linked map four final priorities, the deque T-104 before T-208, and the copy sorted to [1, 3, 4, 5].

Choose Java Course: Concepts, MCQs & Coding Questions if you are still building language fundamentals. Move to DSA using Java: Placement Preparation Course when you are ready to apply collections in data-structure and interview problems.