Java Collections
Collections Overview
Complete lesson for Collections Overview using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Collections Overview
Section: Java Collections. The Java Collections Framework: List, Set, Queue, Deque, and Map — hierarchy, implementations, common methods, the Collections utility class, sorting, complexity, and choosing the right collection with real-life examples.
What is the Java Collections Framework?
- A collection is an object that holds a group of other objects. The Collections Framework (package
java.util) is a ready-made set of interfaces, classes, and algorithms for storing and processing such groups. - It has three parts: interfaces (
List,Set,Queue,Deque,Map), implementations (ArrayList,HashSet,HashMap, ...), and algorithms (Collections.sort,shuffle,max, ...). - Real life: your phone already uses all of them. The playlist is a
List(order, repeats allowed), Aadhaar numbers are aSet(no duplicates), the bank token line is aQueue(first come, first served), and contacts are aMap(name to number). - Benefits: no need to write your own data structures, well-tested and fast code, a common API, and easy switching between implementations.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class CollectionsTour {
public static void main(String[] args) {
List<String> playlist = new ArrayList<>(List.of("Kesariya", "Jai Ho", "Kesariya")); // order + repeats
Set<String> aadhaar = new HashSet<>(List.of("1111", "2222", "1111")); // unique only
Queue<String> tokens = new ArrayDeque<>(List.of("T1", "T2", "T3")); // first in, first out
Map<String, String> contacts = new HashMap<>(); // key -> value
contacts.put("Asha", "98480 11111");
contacts.put("Ravi", "90000 22222");
System.out.println("Playlist: " + playlist); // [Kesariya, Jai Ho, Kesariya]
System.out.println("Unique IDs: " + aadhaar.size()); // 2
System.out.println("Now serving: " + tokens.poll()); // T1
System.out.println("Call Ravi: " + contacts.get("Ravi"));
}
} Differences between arrays and collections
- Real life: an array is an egg tray with exactly 12 slots. A collection is a shopping bag that stretches as you add items and comes with helpers to search, sort, and remove.
| Point | Array | Collection |
|---|---|---|
| Size | Fixed when created | Grows and shrinks automatically |
| Element types | Primitives and objects | Objects only (primitives are auto-boxed: int to Integer) |
| Built-in methods | Only length (helpers in Arrays) | Many: add, remove, contains, sort, stream, ... |
| Data structures | Only an indexed block | List, Set, Queue, Deque, Map, sorted and hashed variants |
| Duplicates control | Manual | Set and Map keys reject duplicates automatically |
| Type safety | Yes (String[]) | Yes with generics (List<String>) |
| Performance / memory | Fastest, least memory | Small overhead for flexibility |
| Sorting | Arrays.sort(arr) | Collections.sort(list) or list.sort(...) |
| Real life | Egg tray with 12 fixed slots | Stretchable shopping bag |
import java.util.ArrayList;
import java.util.List;
public class ArrayVsList {
public static void main(String[] args) {
String[] seats = new String[3]; // fixed: exactly 3 seats
seats[0] = "Asha";
seats[1] = "Ravi";
seats[2] = "Kiran";
// seats[3] = "Meena"; // ArrayIndexOutOfBoundsException
List<String> guests = new ArrayList<>(); // grows as needed
guests.add("Asha");
guests.add("Ravi");
guests.add("Kiran");
guests.add("Meena"); // no problem
guests.remove("Ravi"); // built-in remove
System.out.println(guests + " contains Kiran? " + guests.contains("Kiran"));
// [Asha, Kiran, Meena] contains Kiran? true
}
} Collection hierarchy
Iterableis the top: anything iterable works in a for-each loop.CollectionextendsIterableand is the parent ofList,Set, andQueue.Mapis a separate hierarchy. It is part of the framework but does not extendCollection, because it stores key-value pairs.- Program to interfaces: declare variables as
List,Set,Map,Deque, and choose the class only atnew.
Iterable<E>
└── Collection<E>
├── List<E> ............ ArrayList, LinkedList, Vector, Stack(legacy)
├── Set<E> ............. HashSet, LinkedHashSet
│ └── SortedSet<E>
│ └── NavigableSet<E> ... TreeSet
└── Queue<E> ........... PriorityQueue
└── Deque<E> ...... ArrayDeque, LinkedList
Map<K, V> (separate root, not a Collection)
├── HashMap ──── LinkedHashMap
├── Hashtable(legacy)
└── SortedMap<K, V>
└── NavigableMap<K, V> ... TreeMap Differences between List, Set, Queue, and Map
| Point | List | Set | Queue / Deque | Map |
|---|---|---|---|---|
| Stores | Elements | Elements | Elements | Key-value pairs |
| Duplicates | Allowed | Not allowed | Allowed | Keys unique, values can repeat |
| Order | Insertion order, by index | None, insertion, or sorted | FIFO, LIFO, or priority | None, insertion, or sorted by key |
| Index access | Yes: get(i) | No | No (only head / tail) | By key: get(key) |
| Main classes | ArrayList, LinkedList | HashSet, LinkedHashSet, TreeSet | ArrayDeque, PriorityQueue | HashMap, LinkedHashMap, TreeMap |
| Extends Collection? | Yes | Yes | Yes | No |
| Real life | Playlist, to-do list | Aadhaar numbers, unique visitors | Bank token line, print jobs | Phone contacts, dictionary |
Common implementation classes compared
| Class | Implements | Internal structure | Order | Duplicates | null | Thread-safe |
|---|---|---|---|---|---|---|
ArrayList | List | Resizable array | Insertion | Yes | Yes | No |
LinkedList | List, Deque | Doubly linked list | Insertion | Yes | Yes | No |
Vector | List | Synchronized resizable array | Insertion | Yes | Yes | Yes (legacy) |
HashSet | Set | Hash table (a HashMap inside) | None | No | One | No |
LinkedHashSet | Set | Hash table + linked list | Insertion | No | One | No |
TreeSet | NavigableSet | Red-black tree | Sorted | No | No | No |
PriorityQueue | Queue | Binary heap | Smallest (or by Comparator) at head | Yes | No | No |
ArrayDeque | Deque | Resizable circular array | Both ends | Yes | No | No |
HashMap | Map | Array of buckets (lists or trees) | None | Keys unique | One null key | No |
LinkedHashMap | Map | Hash table + linked list | Insertion or access | Keys unique | One null key | No |
TreeMap | NavigableMap | Red-black tree | Sorted by key | Keys unique | No null key | No |
Hashtable | Map | Synchronized hash table | None | Keys unique | No | Yes (legacy) |
ConcurrentHashMap | ConcurrentMap | Hash table with fine-grained locking | None | Keys unique | No | Yes |
Real-life examples: which collection to use
| Real-life need | Collection | Why |
|---|---|---|
| Songs in a playlist (repeats allowed) | ArrayList | Keeps order, allows duplicates, fast index access |
| Unique email IDs of website visitors | HashSet | Rejects duplicates, fast contains |
| Unique visitors in first-visit order | LinkedHashSet | Unique plus insertion order |
| Exam ranks or a sorted name list | TreeSet / TreeMap | Always sorted |
| Bank token line | ArrayDeque as Queue | First in, first out |
| Browser back button / undo | ArrayDeque as stack | Last in, first out |
| Hospital emergency room | PriorityQueue | Most critical patient first |
| Phone contacts (name to number) | HashMap | Fast lookup by key |
| Recently opened files | LinkedHashMap (access order) | Easy LRU cache |
| Live vote counts from many threads | ConcurrentHashMap | Thread-safe updates |
Collection interface methods
- These methods work on every
List,Set, andQueue, because they come from theCollectioninterface.
| Method | What it does | Example |
|---|---|---|
add(e) | Adds an element; returns false if a Set already has it | books.add("Java") |
addAll(c) | Adds every element of another collection | books.addAll(newArrivals) |
remove(o) | Removes one matching element | books.remove("Java") |
removeAll(c) | Removes every element that is in c | books.removeAll(damaged) |
retainAll(c) | Keeps only elements also in c (intersection) | books.retainAll(requested) |
removeIf(predicate) | Removes elements matching a condition | books.removeIf(b -> b.isEmpty()) |
contains(o) | Checks if an element exists | books.contains("Java") |
containsAll(c) | Checks if all elements of c exist | books.containsAll(syllabus) |
size() | Number of elements | books.size() |
isEmpty() | True if no elements | books.isEmpty() |
clear() | Removes everything | books.clear() |
iterator() | Returns an Iterator for looping and safe removal | books.iterator() |
toArray() | Copies elements into an array | books.toArray(new String[0]) |
stream() | Creates a Stream for filter, map, collect | books.stream().filter(...) |
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class LibraryShelf {
public static void main(String[] args) {
Collection<String> shelf = new ArrayList<>();
shelf.add("Java Basics");
shelf.addAll(List.of("DSA in Java", "Spring Boot", "Python 101"));
System.out.println(shelf.size() + " books"); // 4 books
System.out.println(shelf.contains("Spring Boot")); // true
shelf.remove("Python 101"); // issued to a student
shelf.removeIf(b -> b.startsWith("DSA")); // sent for binding
System.out.println(shelf); // [Java Basics, Spring Boot]
shelf.retainAll(List.of("Spring Boot", "React")); // keep only requested books
System.out.println(shelf); // [Spring Boot]
shelf.clear();
System.out.println(shelf.isEmpty()); // true
}
} Map interface methods
| Method | What it does | Example |
|---|---|---|
put(k, v) | Adds or replaces the value for a key | contacts.put("Asha", "98480") |
get(k) | Value for a key, or null | contacts.get("Asha") |
getOrDefault(k, d) | Value or a default if missing | stock.getOrDefault("pen", 0) |
putIfAbsent(k, v) | Adds only if the key is missing | settings.putIfAbsent("theme", "dark") |
containsKey(k) / containsValue(v) | Checks keys or values | contacts.containsKey("Ravi") |
remove(k) | Removes the entry for a key | contacts.remove("Ravi") |
merge(k, v, fn) | Combines a new value with the old one | count.merge(word, 1, Integer::sum) |
computeIfAbsent(k, fn) | Creates a value when the key is missing | groups.computeIfAbsent(city, c -> new ArrayList<>()) |
keySet() / values() / entrySet() | Views of keys, values, or entries | for (var e : map.entrySet()) |
forEach((k, v) -> ...) | Loops over every entry | map.forEach((k, v) -> print(k, v)) |
size() / isEmpty() / clear() | Same meaning as in Collection | contacts.size() |
import java.util.HashMap;
import java.util.Map;
public class PhoneBook {
public static void main(String[] args) {
Map<String, String> contacts = new HashMap<>();
contacts.put("Asha", "98480 11111");
contacts.put("Ravi", "90000 22222");
contacts.put("Asha", "98480 99999"); // same key: value replaced
contacts.putIfAbsent("Kiran", "77777 33333");
System.out.println(contacts.get("Asha")); // 98480 99999
System.out.println(contacts.getOrDefault("Meena", "Not saved"));
System.out.println(contacts.containsKey("Ravi")); // true
Map<String, Integer> calls = new HashMap<>();
for (String name : new String[] { "Asha", "Ravi", "Asha", "Asha" }) {
calls.merge(name, 1, Integer::sum); // count calls per person
}
for (Map.Entry<String, Integer> e : calls.entrySet()) {
System.out.println(e.getKey() + " called " + e.getValue() + " times");
}
}
} Ways to iterate a collection
- Use for-each for simple reading,
Iteratorwhen you must remove while looping,ListIteratorto go backwards or replace, andforEachor streams for short lambda code. - For maps, loop over
entrySet()to get the key and value together without extra lookups.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class IterateWays {
public static void main(String[] args) {
List<String> cities = new ArrayList<>(List.of("Hyderabad", "Pune", "Chennai", "Delhi"));
for (int i = 0; i < cities.size(); i++) { // 1. index loop (List only)
System.out.print(cities.get(i) + " ");
}
System.out.println();
for (String c : cities) { // 2. for-each
System.out.print(c + " ");
}
System.out.println();
Iterator<String> it = cities.iterator(); // 3. Iterator: safe removal
while (it.hasNext()) {
if (it.next().startsWith("D")) it.remove();
}
cities.forEach(c -> System.out.print(c + " ")); // 4. forEach + lambda
System.out.println();
ListIterator<String> back = cities.listIterator(cities.size()); // 5. backwards
while (back.hasPrevious()) {
System.out.print(back.previous() + " ");
}
System.out.println();
cities.stream() // 6. Stream
.filter(c -> c.length() > 4)
.forEach(System.out::println);
Map<String, Integer> pin = Map.of("Pune", 411001, "Chennai", 600001);
for (Map.Entry<String, Integer> e : pin.entrySet()) { // 7. Map entries
System.out.println(e.getKey() + " -> " + e.getValue());
}
}
} Generics with collections
- Always give collections a type:
List<String>,Map<String, Integer>. The compiler then blocks wrong types and you need no casts. - Raw types (
Listwithout<>) compile with warnings and fail at runtime withClassCastException. - Use the diamond
<>on the right side:new ArrayList<>(). Collections hold objects, soList<int>is not allowed; useList<Integer>.
import java.util.ArrayList;
import java.util.List;
public class GenericsInCollections {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
List raw = new ArrayList(); // raw type: anything goes
raw.add("Asha");
raw.add(42); // compiles
try {
String s = (String) raw.get(1); // fails only at runtime
System.out.println(s);
} catch (ClassCastException e) {
System.out.println("Raw list error: " + e.getClass().getSimpleName());
}
List<String> names = new ArrayList<>(); // generic: type checked by the compiler
names.add("Asha");
// names.add(42); // compile error: caught early
String first = names.get(0); // no cast needed
System.out.println("First: " + first);
List<Integer> marks = new ArrayList<>(); // List<int> is not allowed
marks.add(95); // auto-boxing int -> Integer
System.out.println(marks);
}
} Collections utility class
java.util.Collections(with an s) is a helper class full of static methods. Do not confuse it with theCollectioninterface.
| Method | What it does | Real life |
|---|---|---|
Collections.sort(list) | Sorts in natural order (or with a Comparator) | Arrange students by roll number |
Collections.reverse(list) | Reverses the order | Show latest messages first |
Collections.shuffle(list) | Random order | Lucky draw, shuffle songs |
Collections.max(c) / min(c) | Largest or smallest element | Topper and lowest score |
Collections.frequency(c, o) | Counts occurrences | How many times 100 was scored |
Collections.binarySearch(list, key) | Fast search in a sorted list | Find a page in a sorted index |
Collections.swap(list, i, j) | Swaps two positions | Swap two players in a batting order |
Collections.nCopies(n, o) | Read-only list of n copies | Print 3 cheers |
Collections.unmodifiableList(list) | Read-only view | Share a menu that customers cannot edit |
Collections.synchronizedList(list) | Thread-safe wrapper | Simple shared list across threads |
Collections.emptyList() | Shared empty immutable list | Return "no results" safely |
Collections.addAll(c, a, b, ...) | Adds many elements at once | Add several items to a cart |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LuckyDraw {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>(List.of(72, 95, 60, 88, 95));
System.out.println("Top score: " + Collections.max(scores)); // 95
System.out.println("Lowest: " + Collections.min(scores)); // 60
System.out.println("95 scored " + Collections.frequency(scores, 95) + " times"); // 2
Collections.sort(scores);
System.out.println("Sorted: " + scores); // [60, 72, 88, 95, 95]
System.out.println("Index of 88: " + Collections.binarySearch(scores, 88)); // 2
Collections.reverse(scores);
System.out.println("Rank list: " + scores); // [95, 95, 88, 72, 60]
List<String> tickets = new ArrayList<>(List.of("A1", "A2", "A3", "A4", "A5"));
Collections.shuffle(tickets);
System.out.println("Lucky winner: " + tickets.get(0)); // random
List<String> readOnly = Collections.unmodifiableList(tickets);
// readOnly.add("A6"); // UnsupportedOperationException
System.out.println(readOnly.size() + " tickets, " + Collections.nCopies(3, "Hip hip hooray!"));
}
} Differences between Comparable and Comparator
- Real life: a product has one natural order printed on the shelf (by price) — that is
Comparable. Customers can still sort the same products by rating or name using their own rule — that isComparator.
| Point | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T other) | compare(T a, T b) |
| Where written | Inside the class being sorted | Separate class, lambda, or method reference |
| Number of orders | One natural order | Any number of custom orders |
| Changes the class? | Yes, the class implements it | No, works even on classes you cannot edit |
| Used by | Collections.sort(list), TreeSet, TreeMap by default | list.sort(cmp), new TreeSet<>(cmp) |
| Examples in JDK | String, Integer, LocalDate | Comparator.comparing(...), String.CASE_INSENSITIVE_ORDER |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Product implements Comparable<Product> {
final String name;
final int price;
final double rating;
Product(String name, int price, double rating) {
this.name = name;
this.price = price;
this.rating = rating;
}
@Override
public int compareTo(Product other) { // natural order: by price
return Integer.compare(this.price, other.price);
}
@Override
public String toString() {
return name + "(Rs." + price + ", " + rating + ")";
}
}
public class SortProducts {
public static void main(String[] args) {
List<Product> items = new ArrayList<>(List.of(
new Product("Earbuds", 1999, 4.1),
new Product("Charger", 799, 4.5),
new Product("Watch", 2999, 3.9)
));
Collections.sort(items); // Comparable
System.out.println("By price: " + items);
items.sort(Comparator.comparingDouble((Product p) -> p.rating).reversed()); // Comparator
System.out.println("By rating: " + items);
items.sort(Comparator.comparing((Product p) -> p.name)); // Comparator
System.out.println("By name: " + items);
}
} Immutable and unmodifiable collections
List.of,Set.of,Map.of(Java 9) create immutable collections: no add, remove, or set, and nonullelements.Collections.unmodifiableList(list)is a read-only view: you cannot change it, but changes to the original list show through.List.copyOf(list)(Java 10) makes an independent immutable snapshot.- Real life: a printed menu card is immutable; a live CCTV screen of the kitchen is a read-only view (you cannot touch, but you see changes).
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ImmutableDemo {
public static void main(String[] args) {
List<String> days = List.of("Mon", "Tue", "Wed");
try {
days.add("Thu");
} catch (UnsupportedOperationException e) {
System.out.println("List.of is immutable");
}
List<String> menu = new ArrayList<>(List.of("Idli", "Dosa"));
List<String> view = Collections.unmodifiableList(menu); // read-only view
List<String> copy = List.copyOf(menu); // independent snapshot
menu.add("Vada");
System.out.println("View: " + view); // [Idli, Dosa, Vada] (sees the change)
System.out.println("Copy: " + copy); // [Idli, Dosa] (does not)
}
} Advanced — Collections Overview
Complexity cheat sheet (amortized / average)
| Collection | Add | Remove | Search / get | Notes |
|---|---|---|---|---|
ArrayList | O(1) at end (amortized) | O(n) | get(i) O(1); contains O(n) | Best default List |
LinkedList | O(1) at ends | O(1) at ends; O(n) by value | O(n) | Extra memory per node |
HashSet / HashMap | O(1) | O(1) | O(1) | Needs good hashCode; worst case O(log n) with tree bins |
LinkedHashSet / LinkedHashMap | O(1) | O(1) | O(1) | Keeps insertion or access order |
TreeSet / TreeMap | O(log n) | O(log n) | O(log n) | Sorted; supports floor, ceiling, ranges |
ArrayDeque | O(1) at ends | O(1) at ends | O(n) | Best Stack and Queue |
PriorityQueue | O(log n) | poll O(log n) | peek O(1) | Heap, not fully sorted |
ConcurrentHashMap | O(1) | O(1) | O(1) | Thread-safe without locking the whole map |
How to choose the right collection
| If you need... | Use | Avoid |
|---|---|---|
| An ordered list with index access | ArrayList | LinkedList (rarely faster) |
| No duplicates, fast lookup | HashSet | List.contains in a loop (O(n)) |
| No duplicates in insertion order | LinkedHashSet | Sorting a HashSet output |
| Always sorted, range queries | TreeSet / TreeMap | Sorting a list after every insert |
| FIFO queue or LIFO stack | ArrayDeque | Stack and Vector (legacy, synchronized) |
| Process by priority | PriorityQueue | Sorting the whole list each time |
| Key to value lookup | HashMap | Two parallel lists |
| Map in insertion order or an LRU cache | LinkedHashMap | Custom linked structures |
| Shared map across threads | ConcurrentHashMap | Hashtable, unsynchronized HashMap |
| Fixed constant data | List.of / Set.of / Map.of | Mutable lists exposed publicly |
| Keys are enum constants | EnumMap / EnumSet | HashMap with enum keys (slower) |
equals and hashCode contract
HashSet,HashMap, andLinkedHash*usehashCode()to find the bucket andequals()to compare inside it.- Rule: if two objects are equal by
equals, they must have the samehashCode. Always override both together, using the same fields. - Never change a field used in
hashCodewhile the object is inside aHashSetor used as aHashMapkey — the object gets "lost". - For
TreeSetandTreeMap,compareTo(or the Comparator) decides equality, so keep it consistent withequals. - Real life: a school identifies students by roll number. Two ID card scans with the same roll number are the same student.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class Student {
final int roll;
final String name;
Student(int roll, String name) {
this.roll = roll;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student s)) return false;
return roll == s.roll; // same roll number = same student
}
@Override
public int hashCode() {
return Objects.hash(roll); // same field as equals
}
}
public class Attendance {
public static void main(String[] args) {
Set<Student> present = new HashSet<>();
present.add(new Student(101, "Asha"));
present.add(new Student(101, "Asha")); // same ID card scanned twice
present.add(new Student(102, "Ravi"));
System.out.println("Present: " + present.size()); // 2 (3 without equals and hashCode)
}
} Differences between fail-fast and fail-safe iterators
- Fail-fast iterators (most of
java.util) throwConcurrentModificationExceptionif the collection is structurally changed during iteration, except through the iterator itself. - Fail-safe (weakly consistent or snapshot) iterators in
java.util.concurrentnever throw it; they work on a snapshot or tolerate concurrent changes. - Real life: a teacher taking attendance stops and complains if someone changes the register mid-way (fail-fast). A photocopy of the register can be read calmly while the original changes (fail-safe).
| Point | Fail-fast | Fail-safe |
|---|---|---|
| Examples | ArrayList, HashMap, HashSet iterators | CopyOnWriteArrayList, ConcurrentHashMap iterators |
| Change during loop | Throws ConcurrentModificationException | No exception |
| Works on | The original collection | A snapshot or a weakly consistent view |
| Sees new changes? | Not applicable (it fails) | Maybe not (snapshot may be old) |
| Memory | No extra copy | May copy (copy-on-write) |
| Safe removal | iterator.remove() or removeIf | Direct changes allowed |
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class FailFastDemo {
public static void main(String[] args) {
List<String> cart = new ArrayList<>(List.of("Milk", "Bread", "Chips"));
try {
for (String item : cart) {
if (item.equals("Chips")) cart.remove(item); // changing while looping
}
} catch (ConcurrentModificationException e) {
System.out.println("Fail-fast: ConcurrentModificationException");
}
List<String> cart2 = new ArrayList<>(List.of("Milk", "Bread", "Chips"));
cart2.removeIf(item -> item.equals("Chips")); // safe way
System.out.println(cart2); // [Milk, Bread]
List<String> safe = new CopyOnWriteArrayList<>(List.of("Milk", "Bread"));
for (String item : safe) {
safe.add("Eggs"); // loops over a snapshot
}
System.out.println(safe); // [Milk, Bread, Eggs, Eggs]
}
} Thread-safe collections
- Normal collections are not thread-safe. Sharing an
ArrayListorHashMapbetween threads that write can corrupt data.
| Option | How it works | Use when |
|---|---|---|
Collections.synchronizedList/Map/Set | Wraps every method in a lock | Low traffic; must still lock manually while iterating |
Vector / Hashtable | Legacy classes with synchronized methods | Only for old code |
ConcurrentHashMap | Fine-grained locking and CAS; atomic merge, compute | Shared maps, counters, caches |
CopyOnWriteArrayList | Copies the array on every write | Many reads, very few writes (listeners) |
ConcurrentLinkedQueue | Lock-free queue | High-throughput producer-consumer without blocking |
ArrayBlockingQueue / LinkedBlockingQueue | put waits when full, take waits when empty | Producer-consumer pipelines |
ConcurrentSkipListMap | Sorted, concurrent map | Shared leaderboards and sorted data |
Legacy collection classes
- Before Java 1.2, Java had
Vector,Stack,Hashtable, andEnumeration. They still work but are synchronized (slower) and have older APIs.
| Legacy class | Problem | Modern replacement |
|---|---|---|
Vector | Every method synchronized, slower | ArrayList (or CopyOnWriteArrayList) |
Stack | Extends Vector, exposes index methods | ArrayDeque with push / pop |
Hashtable | Locks the whole table, no nulls | HashMap or ConcurrentHashMap |
Enumeration | No remove, long method names | Iterator |
Properties | Extends Hashtable | Still fine for .properties config files |
null handling across collections
| Collection | null elements / keys | null values (maps) |
|---|---|---|
ArrayList, LinkedList | Allowed (many) | - |
HashSet, LinkedHashSet | One null | - |
TreeSet | Not allowed (natural order) | - |
ArrayDeque, PriorityQueue | Not allowed | - |
HashMap, LinkedHashMap | One null key | Allowed |
TreeMap | No null key (natural order) | Allowed |
Hashtable, ConcurrentHashMap | Not allowed | Not allowed |
List.of, Set.of, Map.of | Not allowed | Not allowed |
Sequenced collections (Java 21)
- Java 21 added
SequencedCollection,SequencedSet, andSequencedMapfor collections with a defined order. - New common methods:
getFirst(),getLast(),addFirst(),addLast(),removeFirst(),removeLast(), andreversed(). Maps getfirstEntry(),lastEntry(),pollFirstEntry(), and more. - Real life: a queue at a ticket counter — you often need just the first and last person, or the line in reverse.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedMap;
public class SequencedDemo {
public static void main(String[] args) {
List<String> line = new ArrayList<>(List.of("Asha", "Ravi", "Kiran"));
System.out.println(line.getFirst() + " ... " + line.getLast()); // Asha ... Kiran
line.addFirst("VIP"); // jumps the line
System.out.println(line.reversed()); // [Kiran, Ravi, Asha, VIP]
LinkedHashSet<String> recentApps = new LinkedHashSet<>(List.of("Maps", "Gmail", "YouTube"));
System.out.println("Latest app: " + recentApps.getLast()); // YouTube
SequencedMap<String, Integer> rounds = new LinkedHashMap<>();
rounds.put("Round 1", 40);
rounds.put("Round 2", 55);
System.out.println(rounds.firstEntry() + " / " + rounds.lastEntry()); // Round 1=40 / Round 2=55
}
} Collections with streams
- Every collection can produce a
Streamwithstream(). Streams filter, transform, group, and summarise data in a readable pipeline. Collectors.groupingBy,counting,summingInt,toMap, andjoiningturn streams back into collections.- Real life: a food delivery app grouping orders by city and listing big orders.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class OrdersReport {
record Order(String city, String item, int amount) { }
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("Hyderabad", "Biryani", 350),
new Order("Pune", "Misal", 120),
new Order("Hyderabad", "Haleem", 280),
new Order("Chennai", "Dosa", 90)
);
Map<String, Integer> salesByCity = orders.stream()
.collect(Collectors.groupingBy(Order::city, Collectors.summingInt(Order::amount)));
System.out.println(salesByCity); // Hyderabad=630, Pune=120, Chennai=90 (order may vary)
List<String> bigOrders = orders.stream()
.filter(o -> o.amount() > 200)
.map(Order::item)
.toList(); // Java 16
System.out.println(bigOrders); // [Biryani, Haleem]
}
} Collections best practices
| Do | Do not |
|---|---|
Declare with interfaces: List<String> list = new ArrayList<>() | Declare as ArrayList<String> everywhere |
| Always use generics | Use raw types like List |
| Pick by need: List, Set, Queue, or Map | Use ArrayList for everything |
Override equals and hashCode together for keys | Use mutable objects as map keys |
Use removeIf or Iterator.remove to delete while looping | Call list.remove inside a for-each loop |
Return empty collections, not null | Force callers to check for null |
Use List.of / List.copyOf for read-only data | Expose internal mutable lists from getters |
| Set an initial capacity for very large lists or maps | Let a huge map resize again and again |
| Use concurrent collections for shared data | Share HashMap between writing threads |
Tricky Interview Points
Q1) What is the Java Collections Framework?
Answer A unified set of interfaces (List, Set, Queue, Deque, Map), implementations (ArrayList, HashSet, HashMap, ...), and algorithms (in the Collections class) in java.util for storing and processing groups of objects.
Q2) What is the difference between an array and a collection?
Answer An array has a fixed size and can hold primitives. A collection grows dynamically, holds only objects, and provides many ready-made methods and data structures.
Q3) What is the difference between Collection and Collections?
Answer Collection is the root interface for List, Set, and Queue. Collections is a utility class with static methods such as sort, reverse, shuffle, max, and unmodifiableList.
Q4) Is Map a part of the Collection interface?
Answer No. Map is part of the framework but does not extend Collection, because it stores key-value pairs. You can view its keySet, values, and entrySet as collections.
Q5) What is the difference between List and Set?
Answer List keeps insertion order, allows duplicates, and supports index access. Set does not allow duplicates and has no index.
Q6) What is the difference between HashSet, LinkedHashSet, and TreeSet?
Answer HashSet has no order and O(1) operations. LinkedHashSet keeps insertion order. TreeSet keeps elements sorted with O(log n) operations and does not allow null.
Q7) What is the difference between HashMap, LinkedHashMap, and TreeMap?
Answer HashMap has no order. LinkedHashMap keeps insertion (or access) order. TreeMap keeps keys sorted. HashMap and LinkedHashMap allow one null key; TreeMap does not with natural ordering.
Q8) What is the difference between ArrayList and LinkedList?
Answer ArrayList uses a resizable array with O(1) index access. LinkedList uses a doubly linked list with O(1) insertion at the ends but O(n) index access and more memory. ArrayList is usually faster in practice.
Q9) Which collection would you use for a FIFO queue or a stack?
Answer ArrayDeque for both: offer and poll for a queue, push and pop for a stack. It is faster than the legacy Stack class and LinkedList.
Q10) What is a PriorityQueue?
Answer A queue backed by a binary heap where the head is always the smallest element by natural order or a Comparator. Iteration order is not sorted.
Q11) Why should we override equals and hashCode for HashMap keys?
Answer HashMap finds the bucket with hashCode and matches with equals. If they are inconsistent, equal keys land in different buckets and lookups fail or duplicates appear.
Q12) What is the difference between Comparable and Comparator?
Answer Comparable defines a natural order inside the class with compareTo. Comparator defines external custom orders with compare and can be written as a lambda.
Q13) What is the difference between fail-fast and fail-safe iterators?
Answer Fail-fast iterators throw ConcurrentModificationException if the collection is changed during iteration. Fail-safe iterators of concurrent collections work on a snapshot or a weakly consistent view and do not throw.
Q14) How do you remove elements while iterating?
Answer Use Iterator.remove() or collection.removeIf(predicate). Calling list.remove inside a for-each loop causes ConcurrentModificationException.
Q15) What is the difference between List.of and Collections.unmodifiableList?
Answer List.of creates a truly immutable list that rejects nulls. unmodifiableList is a read-only view over another list; changes to the original are visible through it.
Q16) How can you make a collection thread-safe?
Answer Use Collections.synchronizedList or synchronizedMap wrappers, or better, concurrent classes like ConcurrentHashMap, CopyOnWriteArrayList, and BlockingQueue.
Q17) Which collections do not allow null?
Answer TreeSet and TreeMap keys (natural order), ArrayDeque, PriorityQueue, Hashtable, ConcurrentHashMap, and immutable collections from List.of, Set.of, and Map.of.
Q18) What is the time complexity of get in HashMap?
Answer O(1) on average. In the worst case, a bucket with many collisions becomes a balanced tree (Java 8+), giving O(log n).
Q19) What are legacy collection classes?
Answer Vector, Stack, Hashtable, and Enumeration from Java 1.0. They are synchronized and replaced by ArrayList, ArrayDeque, HashMap or ConcurrentHashMap, and Iterator.
Q20) What are sequenced collections in Java 21?
Answer New interfaces SequencedCollection, SequencedSet, and SequencedMap that give ordered collections common methods like getFirst, getLast, addFirst, removeLast, and reversed.
Simple Programs
Student marks register with Map and List
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class MarksRegister {
public static void main(String[] args) {
Map<String, List<Integer>> register = new TreeMap<>(); // names sorted A-Z
String[][] entries = {
{ "Ravi", "78" }, { "Asha", "92" }, { "Ravi", "85" },
{ "Kiran", "64" }, { "Asha", "88" }, { "Kiran", "71" }
};
for (String[] e : entries) {
register.computeIfAbsent(e[0], k -> new ArrayList<>()).add(Integer.parseInt(e[1]));
}
register.forEach((name, marks) -> {
double avg = marks.stream().mapToInt(Integer::intValue).average().orElse(0);
System.out.printf("%-6s %s avg %.1f%n", name, marks, avg);
});
// Asha [92, 88] avg 90.0
// Kiran [64, 71] avg 67.5
// Ravi [78, 85] avg 81.5
}
} Unique website visitors with LinkedHashSet
import java.util.LinkedHashSet;
import java.util.Set;
public class UniqueVisitors {
public static void main(String[] args) {
String[] log = { "asha@gmail.com", "ravi@yahoo.com", "asha@gmail.com",
"kiran@gmail.com", "ravi@yahoo.com" };
Set<String> visitors = new LinkedHashSet<>(); // unique + first-visit order
for (String email : log) {
if (!visitors.add(email)) { // add returns false for duplicates
System.out.println("Returning visitor: " + email);
}
}
System.out.println("Total visits: " + log.length); // 5
System.out.println("Unique visitors: " + visitors.size()); // 3
System.out.println(visitors);
}
} Word frequency in a review with TreeMap
import java.util.Map;
import java.util.TreeMap;
public class WordFrequency {
public static void main(String[] args) {
String review = "good food good service fast delivery good price";
Map<String, Integer> freq = new TreeMap<>(); // words sorted A-Z
for (String word : review.split(" ")) {
freq.merge(word, 1, Integer::sum);
}
System.out.println(freq);
// {delivery=1, fast=1, food=1, good=3, price=1, service=1}
}
} Hospital emergency room with PriorityQueue
import java.util.Comparator;
import java.util.PriorityQueue;
public class EmergencyRoom {
record Patient(String name, int severity) { } // 1 = most critical
public static void main(String[] args) {
PriorityQueue<Patient> queue = new PriorityQueue<>(Comparator.comparingInt(Patient::severity));
queue.offer(new Patient("Asha (fever)", 4));
queue.offer(new Patient("Ravi (heart attack)", 1));
queue.offer(new Patient("Kiran (fracture)", 2));
queue.offer(new Patient("Meena (cold)", 5));
while (!queue.isEmpty()) {
Patient p = queue.poll(); // most critical first
System.out.println("Treating " + p.name() + " - severity " + p.severity());
}
// Ravi, Kiran, Asha, Meena
}
} Browser back and forward with ArrayDeque
import java.util.ArrayDeque;
import java.util.Deque;
public class BrowserHistory {
private final Deque<String> back = new ArrayDeque<>();
private final Deque<String> forward = new ArrayDeque<>();
private String current = "home";
void visit(String page) {
back.push(current);
current = page;
forward.clear();
System.out.println("Visit: " + current);
}
void goBack() {
if (back.isEmpty()) return;
forward.push(current);
current = back.pop();
System.out.println("Back: " + current);
}
void goForward() {
if (forward.isEmpty()) return;
back.push(current);
current = forward.pop();
System.out.println("Forward: " + current);
}
public static void main(String[] args) {
BrowserHistory b = new BrowserHistory();
b.visit("google.com");
b.visit("learncodeguru.com");
b.visit("learncodeguru.com/java");
b.goBack(); // learncodeguru.com
b.goBack(); // google.com
b.goForward(); // learncodeguru.com
}
} Recently opened files (LRU cache) with LinkedHashMap
import java.util.LinkedHashMap;
import java.util.Map;
public class RecentFiles<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
RecentFiles(int capacity) {
super(16, 0.75f, true); // true = access order
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity; // drop the least recently used
}
public static void main(String[] args) {
RecentFiles<String, String> recent = new RecentFiles<>(3);
recent.put("resume.pdf", "Documents");
recent.put("photo.jpg", "Pictures");
recent.put("notes.txt", "Desktop");
recent.get("resume.pdf"); // opened again: now most recent
recent.put("song.mp3", "Music"); // photo.jpg is removed
System.out.println(recent.keySet()); // [notes.txt, resume.pdf, song.mp3]
}
} Supermarket bill summary with List, Map, and Collections
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CartSummary {
public static void main(String[] args) {
List<String> scanned = new ArrayList<>(List.of("Milk", "Bread", "Milk", "Eggs", "Milk", "Bread"));
Map<String, Integer> prices = Map.of("Milk", 30, "Bread", 45, "Eggs", 72);
Map<String, Integer> qty = new LinkedHashMap<>(); // keeps scan order
for (String item : scanned) {
qty.merge(item, 1, Integer::sum);
}
int total = 0;
for (Map.Entry<String, Integer> e : qty.entrySet()) {
int cost = e.getValue() * prices.get(e.getKey());
total += cost;
System.out.printf("%-6s x%d = Rs.%d%n", e.getKey(), e.getValue(), cost);
}
System.out.println("Total = Rs." + total); // 252
System.out.println("Most bought: "
+ Collections.max(qty.entrySet(), Map.Entry.comparingByValue()).getKey()); // Milk
}
} Problem Solving Tricks
- Remember: List = order + duplicates, Set = unique, Queue = line, Map = key to value.
- Map is in the framework but is not a Collection.
- Collection is an interface; Collections (with s) is the utility class.
- Need unique plus insertion order?
LinkedHashSet/LinkedHashMap. Need sorted?TreeSet/TreeMap. - Use
ArrayDequefor both stacks and queues; avoidStack,Vector, andHashtablein new code. - Override
equalsandhashCodetogether, using the same fields, for objects stored in hash collections. - Delete while looping only with
Iterator.remove()orremoveIf. List.of/Set.of/Map.ofare immutable and rejectnull.- Loop maps with
entrySet()to get the key and value in one step. - Measure before switching
ArrayListtoLinkedList;ArrayListwins in most real programs.
Practice Programs List
- Store a playlist in a List, unique song names in a Set, and play counts in a Map from the same input.
- Show the difference between an array and an ArrayList by adding a fifth guest to both.
- Write a method that accepts
Collection<String>and works for both a List and a Set. - Print the same integers from a HashSet, a LinkedHashSet, and a TreeSet and compare the order.
- Use
retainAllto find common subjects between two students. - Build a phone book with HashMap using
put,getOrDefault,putIfAbsent, andremove. - Iterate a list in five different ways, including a ListIterator in reverse.
- Use
Collections.max,frequency,shuffle, andreverseon a list of exam scores. - Sort a list of products by price with Comparable and by rating with a Comparator.
- Create a
Studentclass, add duplicates to a HashSet, then fix it with equals and hashCode. - Trigger
ConcurrentModificationException, then fix it withremoveIf. - Model a bank token queue with ArrayDeque and an emergency room with PriorityQueue.
- Build an LRU cache of the 3 most recently opened files using LinkedHashMap.
- Explain from memory which collections allow
nulland which do not.