Collections Overview

Why Collections?

Arrays have a fixed size and few features. The Collections Framework (java.util) gives ready-made, resizable data structures with methods to add, remove, search and sort.

Iterable
  └── Collection
        ├── List   (ordered, duplicates allowed)   ArrayList, LinkedList
        ├── Set    (no duplicates)                  HashSet, LinkedHashSet, TreeSet
        └── Queue  (processing order)               PriorityQueue
              └── Deque (both ends)                 ArrayDeque, LinkedList

Map (key -> value, not a Collection)               HashMap, LinkedHashMap, TreeMap

Choosing a Collection

NeedUseWhy
Ordered list, fast access by indexArrayListarray-backed, O(1) get
Unique items, fast lookupHashSetO(1) contains
Unique items, sortedTreeSetred-black tree, O(log n)
Key → value lookupHashMapO(1) get/put
Key → value in insertion orderLinkedHashMapkeeps order
Key → value sorted by keyTreeMapsorted keys, range queries
Stack or queueArrayDequefast at both ends
Always take the smallest / highest priorityPriorityQueueheap

Tip: Declare variables with the interface type: List<String> names = new ArrayList<>();. Then you can change the implementation later without touching the rest of the code.

Immutable Factory Methods

Example

List.of, Set.of and Map.of (Java 9+) create small read-only collections.

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        List<String> days = List.of("Mon", "Tue", "Wed");
        Set<Integer> primes = Set.of(2, 3, 5);
        Map<String, Integer> pins = Map.of("Delhi", 110001, "Mumbai", 400001);
        System.out.println(days + " size=" + days.size());
        System.out.println("has 3? " + primes.contains(3));
        System.out.println("Mumbai PIN: " + pins.get("Mumbai"));
        try {
            days.add("Thu");
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of is read-only");
        }
    }
}

Output

[Mon, Tue, Wed] size=3
has 3? true
Mumbai PIN: 400001
List.of is read-only