Advanced Topics

Java Collections Framework

Learn the Java Collections Framework — List, Set, Map, Queue, and how to choose the right collection for your use case.

What is the Collections Framework?

The Java Collections Framework provides a set of classes and interfaces for storing and manipulating groups of objects. It's far more flexible than arrays.

Collections Hierarchy

Collection (interface)
├── List (ordered, allows duplicates)
│   ├── ArrayList
│   ├── LinkedList
│   └── Vector
├── Set (no duplicates)
│   ├── HashSet
│   ├── LinkedHashSet
│   └── TreeSet
└── Queue (FIFO)
    ├── LinkedList
    └── PriorityQueue

Map (key-value pairs, separate hierarchy)
├── HashMap
├── LinkedHashMap
├── TreeMap
└── Hashtable

ArrayList

Dynamic array — most commonly used:

java
import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
names.add("Arjun");
names.add("Priya");
names.add("Rahul");

System.out.println(names.get(0));     // Arjun
System.out.println(names.size());     // 3
names.remove("Priya");
System.out.println(names.contains("Priya"));  // false

for (String name : names) {
    System.out.println(name);
}

HashMap

Key-value pairs:

java
import java.util.HashMap;

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Arjun", 95);
scores.put("Priya", 88);
scores.put("Rahul", 92);

System.out.println(scores.get("Arjun"));  // 95

for (var entry : scores.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

HashSet

Unique elements, no order guaranteed:

java
import java.util.HashSet;

HashSet<String> tags = new HashSet<>();
tags.add("java");
tags.add("oop");
tags.add("java");  // Duplicate — ignored

System.out.println(tags.size());  // 2

Choosing the Right Collection

NeedUse
Ordered list with index accessArrayList
Frequent insertions/deletionsLinkedList
Unique elementsHashSet
Unique + sortedTreeSet
Key-value lookupHashMap
Key-value sorted by keyTreeMap
FIFO queueLinkedList or ArrayDeque

Collections Utility Methods

java
import java.util.Collections;
import java.util.ArrayList;

ArrayList<Integer> nums = new ArrayList<>(List.of(5, 2, 8, 1, 9));

Collections.sort(nums);              // [1, 2, 5, 8, 9]
Collections.reverse(nums);           // [9, 8, 5, 2, 1]
System.out.println(Collections.max(nums));  // 9
System.out.println(Collections.min(nums));  // 1

Summary

  • The Collections Framework provides dynamic, flexible alternatives to arrays
  • List: ordered, allows duplicates (ArrayList, LinkedList)
  • Set: no duplicates (HashSet, TreeSet)
  • Map: key-value pairs (HashMap, TreeMap)
  • Use generics (ArrayList<String>) for type safety
  • Collections utility class provides sorting, searching, and more