Collections

Collections Framework: Overview

The Java Collections Framework (JCF) is a set of interfaces, classes, and algorithms in the java.util package that provide ready-made ways to store, retrieve, and manipulate groups of objects.

In simple words:

Collections = Ready-made data structures (list, set, queue, map) with common methods

Real-Life Example: Containers

Different situations need different containers:

text
1Shopping list → order matters, duplicates allowed → List
2Unique ID cards → no duplicates → Set
3Queue at a ticket counter → first in, first out → Queue
4Phone contacts → name → number (key-value) → Map

Java gives a ready-made container for each need, so you do not have to build them yourself.

Why Collections? (Problems with Arrays)

FeatureArrayCollection
SizeFixedDynamic (grows and shrinks)
Data typePrimitives and objectsObjects only (use wrapper classes)
Ready methodsVery fewMany (add, remove, contains, ...)
Data structuresOnly an indexed sequenceList, Set, Queue, Map, etc.
Type safetyChecked at compile timeChecked with Generics

Collection Hierarchy

Points to notice:

PointExplanation
Collection extends IterableSo every collection can be used in a for-each loop
Map does not extend CollectionIt stores key-value pairs, not single elements
LinkedList implements List and DequeIt can behave as a list and as a queue
Collection is an interfaceCollections (with an "s") is a utility class

The Iterable Interface (Top of the Hierarchy)

Iterable is the root. Any class that implements it can be used in the for-each loop.

MethodPurpose
iterator()Returns an Iterator to traverse elements
forEach()Performs an action on each element (Java 8+)

The Collection Interface: Common Methods

These methods are available in every List, Set, and Queue.

MethodPurpose
boolean add(E e)Adds an element
boolean addAll(Collection c)Adds all elements of another collection
boolean remove(Object o)Removes one occurrence of the element
boolean removeAll(Collection c)Removes all elements that are present in c
boolean retainAll(Collection c)Keeps only elements that are present in c
boolean removeIf(Predicate p)Removes elements matching a condition (Java 8+)
boolean contains(Object o)Checks if the element exists
boolean containsAll(Collection c)Checks if all elements of c exist
int size()Returns the number of elements
boolean isEmpty()Checks if the collection is empty
void clear()Removes all elements
Iterator<E> iterator()Returns an iterator
Object[] toArray()Converts the collection to an array
Stream<E> stream()Returns a stream for processing (Java 8+)

Methods That Are NOT in Collection

Each sub-interface adds its own methods.

InterfaceExtra methods
Listget(i), set(i, e), add(i, e), remove(i), indexOf(), subList(), sort()
SetNo new methods (only adds the "no duplicates" rule)
SortedSet / NavigableSetfirst(), last(), headSet(), tailSet(), floor(), ceiling()
Queueoffer(), poll(), peek(), element(), remove()
DequeaddFirst(), addLast(), pollFirst(), pollLast(), push(), pop()
Mapput(), get(), containsKey(), keySet(), values(), entrySet()

The Map Interface (Separate Hierarchy)

Map stores key-value pairs. Keys are unique, values can repeat.

import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, String> students = new HashMap<>();
students.put(1, "Ravi");
students.put(2, "Anita");
students.put(1, "Kiran"); // same key: old value is replaced
System.out.println(students); // {1=Kiran, 2=Anita}
System.out.println(students.get(2)); // Anita
System.out.println(students.containsKey(1)); // true
System.out.println(students.keySet()); // [1, 2]
System.out.println(students.values()); // [Kiran, Anita]
}
}

Since Map is not a Collection, you can get a collection view of it using keySet(), values(), or entrySet().

Iterating Over Collections

1. For-each Loop

for (String fruit : fruits) {
System.out.println(fruit);
}

2. Iterator

Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
String fruit = it.next();
System.out.println(fruit);
}

3. forEach with Lambda (Java 8+)

fruits.forEach(fruit -> System.out.println(fruit));
fruits.forEach(System.out::println); // method reference

Safe Removal While Iterating

Removing from a collection inside a for-each loop throws ConcurrentModificationException (this is called fail-fast behavior).

// Wrong
for (String f : fruits) {
if (f.equals("Apple")) {
fruits.remove(f); // ConcurrentModificationException
}
}
// Correct: Iterator.remove()
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
if (it.next().equals("Apple")) {
it.remove();
}
}
// Correct: removeIf()
fruits.removeIf(f -> f.equals("Apple"));

Generics in Collections

Generics make collections type safe, so the compiler catches wrong types and no casting is needed.

// Without generics (old style): risky
List list = new ArrayList();
list.add("Hello");
list.add(100);
String s = (String) list.get(1); // ClassCastException at runtime
// With generics: safe
List<String> names = new ArrayList<>();
names.add("Hello");
// names.add(100); // Compile-time error

Collections store objects only, so primitives use wrapper classes:

PrimitiveWrapper
intInteger
doubleDouble
charCharacter
booleanBoolean
text
1List<int> Not allowed
2List<Integer> Correct

Ordering Terms Explained

TermMeaningExample
OrderedElements stay in the order they were added (insertion order)ArrayList, LinkedHashSet
UnorderedNo guarantee about the orderHashSet, HashMap
SortedElements are arranged by a sorting ruleTreeSet, TreeMap

"Ordered" and "sorted" are not the same. Ordered means insertion order. Sorted means arranged by value.

The Collections Utility Class

Collections (with an "s") is a class with static helper methods. It is different from the Collection interface.

Collection (interface)Collections (utility class)
Root interface of the hierarchyClass with static utility methods
Defines add(), remove(), etc.Provides sort(), reverse(), max(), etc.
List<Integer> nums = new ArrayList<>(List.of(30, 10, 20));
Collections.sort(nums); // [10, 20, 30]
Collections.reverse(nums); // [30, 20, 10]
Collections.shuffle(nums); // random order
System.out.println(Collections.max(nums)); // 30
System.out.println(Collections.min(nums)); // 10
System.out.println(Collections.frequency(nums, 10)); // 1
List<Integer> fixed = Collections.unmodifiableList(nums); // read-only view

Sorting: Comparable vs Comparator (Preview)

FeatureComparableComparator
Packagejava.langjava.util
MethodcompareTo(T o)compare(T a, T b)
Sorting logicInside the class (natural order)Outside the class (custom order)
Sorting ordersOnly oneMany

TreeSet, TreeMap, and PriorityQueue use these to decide the order. We will cover them in detail later.

Legacy Classes (Avoid in New Code)

Legacy classModern replacement
VectorArrayList (or CopyOnWriteArrayList for thread safety)
StackArrayDeque
HashtableHashMap (or ConcurrentHashMap for thread safety)

Thread Safety (Preview)

Most collections (ArrayList, HashSet, HashMap) are not thread-safe. For multi-threaded programs, use:

OptionExample
Synchronized wrappersCollections.synchronizedList(list)
Concurrent collections (java.util.concurrent)ConcurrentHashMap, CopyOnWriteArrayList

How to Choose a Collection

text
1Need key-value pairs? → Map
2 Need sorted keys? → TreeMap
3 Need insertion order? → LinkedHashMap
4 Just fast lookup? → HashMap
5
6Need unique elements? → Set
7 Need sorted? → TreeSet
8 Need insertion order? → LinkedHashSet
9 Just fast lookup? → HashSet
10
11Need duplicates and index access? → List
12 Mostly reading by index? → ArrayList
13 Frequent insert/delete at the ends? → LinkedList / ArrayDeque
14
15Need FIFO / LIFO processing? → Queue / Deque (ArrayDeque)
16Need highest/lowest priority first? → PriorityQueue

Key Benefits

BenefitExplanation
ReusabilityReady-made data structures, no need to write your own
PerformanceWell-tested, efficient implementations
ConsistencyCommon methods across all collections
FlexibilitySwitch implementation easily (ArrayList → LinkedList)
Type safetyGenerics catch errors at compile time

Programming to an Interface

A good habit is to declare the variable using the interface type, so you can change the implementation later without changing the rest of the code.

List<String> names = new ArrayList<>(); // ✅ interface on the left
// later: names = new LinkedList<>(); // only one line changes
ArrayList<String> names2 = new ArrayList<>(); // ❌ tied to ArrayList

Interview Definition

The Java Collections Framework is a unified architecture of interfaces, implementation classes, and algorithms in the java.util package for storing and manipulating groups of objects, with Collection and Map as its two root interfaces.

Remember

Collection → List, Set, Queue (common methods live here). Map is separate and stores key-value pairs. Collections is only a utility class.

Next TopicArrayList