Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series Java Programming Java Tutorial Module 10 - Collections and I/O

Java Collections Framework List Set Map Queue Overview

Reviewed & accurate
AI Summary

Introduction

The Java Collections Framework, introduced in Java 1.2, is the standard library for storing and manipulating groups of objects. It provides ready made implementations of lists, sets, maps, and queues, plus the algorithms to sort, search, and shuffle them. This Java Collections Framework overview tutorial walks through the core interfaces, the concrete implementations, and the trade offs between them. By the end you will know which collection to reach for in any real Java project.

Beginners often use ArrayList for everything because it works, but the framework offers much more: LinkedList for frequent middle insertions, HashSet for O(1) membership tests, TreeMap for sorted iteration, and ArrayDeque as the preferred stack and queue. Choosing the right collection is one of the highest leverage decisions in any Java program, because data structure choice affects both correctness and performance.

What is the Java Collections Framework?

The Java Collections Framework is a unified architecture in java.util for representing and manipulating collections. It is organized around two root interfaces: Collection, which extends Iterable and is the parent of List, Set, and Queue; and Map, which is a separate root because maps store key value pairs rather than plain elements. The framework also defines the Iterator interface for traversing collections and the Collections utility class of static algorithms like sort, reverse, and shuffle.

List is an ordered collection that allows duplicates, with ArrayList as the array backed workhorse and LinkedList as the doubly linked alternative. Set is a collection that forbids duplicates, with HashSet for fastest add and contains, LinkedHashSet for predictable iteration order, and TreeSet for sorted order. Queue (and its sub interface Deque) supports FIFO and LIFO semantics, with ArrayDeque and PriorityQueue as the main implementations. Map stores key value pairs with no duplicate keys; HashMap, LinkedHashMap, and TreeMap mirror the three Set implementations respectively.

How the Collections Framework Works in Java

Step 1: Choose the right root interface for your use case: List for ordered with duplicates, Set for unique, Queue for FIFO/LIFO, Map for key value. Step 2: Pick a concrete implementation based on access patterns: ArrayList for random access, LinkedList for frequent insertions at the ends, HashSet for O(1) membership, TreeSet for sorted iteration. Step 3: Use generics to specify element type, for example List<String> so the compiler catches type errors. Step 4: Use the add, remove, contains, size, and isEmpty methods that all collections share.

Step 5: Iterate with the enhanced for loop or the stream API; both rely on the Iterable interface implemented by Collection. Step 6: For maps, iterate entrySet to get both key and value. Step 7: Use the Collections utility class for bulk operations like sort, shuffle, reverse, unmodifiableView, and synchronized wrappers. Step 8: Return unmodifiable views from APIs with List.of, Set.of, and Map.of (immutable since Java 9) to protect internal data.

Java Program Demonstrating the Collections Framework


import java.util.*;
import java.util.concurrent.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        // 1. ArrayList: ordered, allows duplicates, O(1) random access
        List<String> list = new ArrayList<>();
        list.add("alpha");
        list.add("beta");
        list.add("alpha"); // duplicate allowed
        list.add(0, "zeta"); // insert at index 0
        System.out.println("List: " + list);
        System.out.println("List get(2): " + list.get(2));
        System.out.println("List indexOf(alpha): " + list.indexOf("alpha"));
        Collections.sort(list);
        System.out.println("Sorted list: " + list);

        // 2. LinkedList: ordered, allows duplicates, fast add/remove at ends
        LinkedList<String> linked = new LinkedList<>(list);
        linked.addFirst("first");
        linked.addLast("last");
        System.out.println("LinkedList: " + linked);

        // 3. HashSet: no duplicates, O(1) add/contains, no order
        Set<String> hashSet = new HashSet<>();
        hashSet.add("apple");
        hashSet.add("banana");
        hashSet.add("apple"); // ignored, duplicate
        hashSet.add("cherry");
        System.out.println("HashSet: " + hashSet + ", size=" + hashSet.size());

        // 4. LinkedHashSet: no duplicates, preserves insertion order
        Set<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("apple");
        linkedHashSet.add("banana");
        linkedHashSet.add("cherry");
        System.out.println("LinkedHashSet (insertion order): " + linkedHashSet);

        // 5. TreeSet: no duplicates, sorted order
        Set<String> treeSet = new TreeSet<>();
        treeSet.add("cherry");
        treeSet.add("apple");
        treeSet.add("banana");
        System.out.println("TreeSet (sorted): " + treeSet);

        // 6. ArrayDeque: fastest stack and queue
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println("Stack pop: " + stack.pop() + ", remaining: " + stack);

        Deque<Integer> queue = new ArrayDeque<>();
        queue.offer(10);
        queue.offer(20);
        queue.offer(30);
        System.out.println("Queue poll: " + queue.poll() + ", remaining: " + queue);

        // 7. PriorityQueue: heap, head is smallest per natural order
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.offer(50);
        pq.offer(10);
        pq.offer(30);
        while (!pq.isEmpty()) {
            System.out.println("PQ poll: " + pq.poll());
        }

        // 8. HashMap: key value, O(1) get/put, null keys and values allowed
        Map<String, Integer> map = new HashMap<>();
        map.put("apple", 5);
        map.put("banana", 3);
        map.put("cherry", 8);
        map.put("apple", 7); // overwrite
        System.out.println("Map: " + map);
        System.out.println("Map get(apple): " + map.get("apple"));
        System.out.println("Map containsKey(banana): " + map.containsKey("banana"));
        for (Map.Entry<String, Integer> e : map.entrySet()) {
            System.out.println("  entry: " + e.getKey() + " -> " + e.getValue());
        }

        // 9. TreeMap: sorted by keys
        Map<String, Integer> treeMap = new TreeMap<>(map);
        System.out.println("TreeMap (sorted by key): " + treeMap);

        // 10. Immutable collections (Java 9+)
        List<String> immutable = List.of("x", "y", "z");
        Set<Integer> immutableSet = Set.of(1, 2, 3);
        Map<String, Integer> immutableMap = Map.of("a", 1, "b", 2);
        System.out.println("Immutable: " + immutable + " " + immutableSet + " " + immutableMap);

        // 11. Collections utility methods
        List<Integer> nums = new ArrayList<>(List.of(5, 3, 1, 4, 2));
        Collections.sort(nums);
        System.out.println("Sorted nums: " + nums);
        Collections.shuffle(nums);
        System.out.println("Shuffled nums: " + nums);
        Collections.reverse(nums);
        System.out.println("Reversed nums: " + nums);
        System.out.println("Max: " + Collections.max(nums) + ", Min: " + Collections.min(nums));
        System.out.println("Frequency of 3: " + Collections.frequency(nums, 3));

        // 12. Unmodifiable view wraps an existing collection
        List<String> unmod = Collections.unmodifiableList(list);
        try {
            unmod.add("fail");
        } catch (UnsupportedOperationException e) {
            System.out.println("Unmodifiable add rejected: " + e.getClass().getSimpleName());
        }
    }
}

Code Explanation Line by Line

ArrayList is the most common List implementation. Backed by a growable array, it provides O(1) random access via get and O(1) amortized append via add. The demo inserts at index 0 with add(0, "zeta"), which is O(n) because all elements shift right. Collections.sort(list) sorts in place using a stable merge sort, which preserves the relative order of equal elements.

LinkedList is a doubly linked list implementation of List and Deque. addFirst and addLast are O(1), making it useful as a queue or deque. The trade off is that random access get(i) is O(n) because the list must traverse from the head. For most production code ArrayList is preferred; LinkedList is rare outside of academic examples.

HashSet is backed by a hash table and offers O(1) average add, remove, and contains. It forbids duplicates: the second add("apple") is silently ignored. It does not preserve insertion order; the iteration order is determined by hash codes. LinkedHashSet adds a doubly linked list through all entries to preserve insertion order at a small memory cost.

TreeSet is backed by a red black tree and keeps elements in sorted order. Add, remove, and contains are O(log n). The iteration order is the natural ordering of the elements, which requires the element type to implement Comparable or a Comparator to be passed to the constructor. PriorityQueue is a min heap: poll returns the smallest element first, also O(log n) for add and poll.

HashMap is the most common Map implementation, O(1) get and put. It allows one null key and any number of null values. The entrySet view lets you iterate key value pairs without copying. TreeMap is the sorted alternative, backed by a red black tree, with O(log n) operations and iteration in sorted key order.

List.of, Set.of, and Map.of (Java 9+) create truly immutable collections that throw UnsupportedOperationException on add, remove, or put. The unmodifiableList wrapper applies the same protection to an existing mutable collection while still allowing the underlying collection to be modified through other references; for true immutability use List.of or copyOf.

Sample Input and Output

Input:  javac CollectionsDemo.java && java CollectionsDemo
Output:
List: [zeta, alpha, beta, alpha]
List get(2): beta
List indexOf(alpha): 1
Sorted list: [alpha, alpha, beta, zeta]
LinkedList: [first, zeta, alpha, alpha, beta, last]
HashSet: [banana, apple, cherry], size=3
LinkedHashSet (insertion order): [apple, banana, cherry]
TreeSet (sorted): [apple, banana, cherry]
Stack pop: 3, remaining: [2, 1]
Queue poll: 10, remaining: [20, 30]
PQ poll: 10
PQ poll: 30
PQ poll: 50
Map: {banana=3, apple=7, cherry=8}
Map get(apple): 7
Map containsKey(banana): true
  entry: banana -> 3
  entry: apple -> 7
  entry: cherry -> 8
TreeMap (sorted by key): {apple=7, banana=3, cherry=8}
Immutable: [x, y, z] [1, 2, 3] {a=1, b=2}
Sorted nums: [1, 2, 3, 4, 5]
Shuffled nums: [3, 1, 5, 2, 4]
Reversed nums: [4, 2, 5, 1, 3]
Max: 5, Min: 1
Frequency of 3: 1
Unmodifiable add rejected: UnsupportedOperationException

The exact iteration order of HashSet and HashMap varies by hash code, so the order of the printed keys may differ by run. The TreeSet and TreeMap order is stable because it is sorted. The PriorityQueue outputs 10, 30, 50 because poll always returns the smallest. The unmodifiable add is rejected with UnsupportedOperationException.

Common Mistakes to Avoid

First, using ArrayList for frequent insertions in the middle is O(n) per insert; LinkedList or a different data structure may be better. Second, modifying a collection while iterating it with a for-each loop throws ConcurrentModificationException; use the Iterator.remove method or removeIf instead. Third, using HashMap in a multithreaded context without synchronization causes data corruption; use ConcurrentHashMap instead. Fourth, expecting HashSet to preserve insertion order is wrong; use LinkedHashSet.

Fifth, using raw types like List without generics loses compile time type safety and forces casts. Sixth, returning the internal mutable collection from a getter exposes it to external modification; return a defensive copy or an unmodifiable view. Seventh, relying on toString order for testing is brittle; the order is not guaranteed across JVM versions. Eighth, using Vector and Stack (the legacy synchronized collections) is discouraged; prefer ArrayList and ArrayDeque.

Real-World Applications

The Collections Framework appears in every major Java framework. Spring stores beans in a Map inside the application context and exposes MVC handler mappings as List or Map. Hibernate returns query results as List and uses Map for the second level cache. JPA's @ElementCollection stores embedded collections as List or Set. Apache Kafka's consumer stores partition assignments in a Set and offsets in a Map. The Android framework uses collections everywhere: RecyclerView.Adapter wraps a List of items, and Bundle is a Map like structure.

In modern Java, the Stream API is built on top of Collection.stream() and accepts or produces collections via the Collectors utility. The immutable List.of, Set.of, and Map.of factories are the recommended way to create constant collections for configuration, error codes, or lookup tables. The java.util.concurrent package adds thread safe collections like CopyOnWriteArrayList, ConcurrentSkipListMap, and LinkedTransferQueue, which all follow the same Collection interface. Understanding the Collections Framework is therefore the foundation of every Java program above a few hundred lines of code, and it appears in every interview and code review.

Conclusion

We walked through List, Set, Queue, Deque, Map, and PriorityQueue with their main implementations. We saw that ArrayList, HashSet, HashMap, and ArrayDeque are the everyday choices, with LinkedList, TreeSet, TreeMap, and PriorityQueue reserved for specialized needs. The next topics to study are HashMap internals, the Stream API, and generics. Once you can choose the right collection for a given problem, your Java code becomes simpler, faster, and more correct.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments