Skip to main content

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.

L1

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 a Set (no duplicates), the bank token line is a Queue (first come, first served), and contacts are a Map (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.
PointArrayCollection
SizeFixed when createdGrows and shrinks automatically
Element typesPrimitives and objectsObjects only (primitives are auto-boxed: int to Integer)
Built-in methodsOnly length (helpers in Arrays)Many: add, remove, contains, sort, stream, ...
Data structuresOnly an indexed blockList, Set, Queue, Deque, Map, sorted and hashed variants
Duplicates controlManualSet and Map keys reject duplicates automatically
Type safetyYes (String[])Yes with generics (List<String>)
Performance / memoryFastest, least memorySmall overhead for flexibility
SortingArrays.sort(arr)Collections.sort(list) or list.sort(...)
Real lifeEgg tray with 12 fixed slotsStretchable 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

  • Iterable is the top: anything iterable works in a for-each loop.
  • Collection extends Iterable and is the parent of List, Set, and Queue.
  • Map is a separate hierarchy. It is part of the framework but does not extend Collection, because it stores key-value pairs.
  • Program to interfaces: declare variables as List, Set, Map, Deque, and choose the class only at new.
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

PointListSetQueue / DequeMap
StoresElementsElementsElementsKey-value pairs
DuplicatesAllowedNot allowedAllowedKeys unique, values can repeat
OrderInsertion order, by indexNone, insertion, or sortedFIFO, LIFO, or priorityNone, insertion, or sorted by key
Index accessYes: get(i)NoNo (only head / tail)By key: get(key)
Main classesArrayList, LinkedListHashSet, LinkedHashSet, TreeSetArrayDeque, PriorityQueueHashMap, LinkedHashMap, TreeMap
Extends Collection?YesYesYesNo
Real lifePlaylist, to-do listAadhaar numbers, unique visitorsBank token line, print jobsPhone contacts, dictionary

Common implementation classes compared

ClassImplementsInternal structureOrderDuplicatesnullThread-safe
ArrayListListResizable arrayInsertionYesYesNo
LinkedListList, DequeDoubly linked listInsertionYesYesNo
VectorListSynchronized resizable arrayInsertionYesYesYes (legacy)
HashSetSetHash table (a HashMap inside)NoneNoOneNo
LinkedHashSetSetHash table + linked listInsertionNoOneNo
TreeSetNavigableSetRed-black treeSortedNoNoNo
PriorityQueueQueueBinary heapSmallest (or by Comparator) at headYesNoNo
ArrayDequeDequeResizable circular arrayBoth endsYesNoNo
HashMapMapArray of buckets (lists or trees)NoneKeys uniqueOne null keyNo
LinkedHashMapMapHash table + linked listInsertion or accessKeys uniqueOne null keyNo
TreeMapNavigableMapRed-black treeSorted by keyKeys uniqueNo null keyNo
HashtableMapSynchronized hash tableNoneKeys uniqueNoYes (legacy)
ConcurrentHashMapConcurrentMapHash table with fine-grained lockingNoneKeys uniqueNoYes

Real-life examples: which collection to use

Real-life needCollectionWhy
Songs in a playlist (repeats allowed)ArrayListKeeps order, allows duplicates, fast index access
Unique email IDs of website visitorsHashSetRejects duplicates, fast contains
Unique visitors in first-visit orderLinkedHashSetUnique plus insertion order
Exam ranks or a sorted name listTreeSet / TreeMapAlways sorted
Bank token lineArrayDeque as QueueFirst in, first out
Browser back button / undoArrayDeque as stackLast in, first out
Hospital emergency roomPriorityQueueMost critical patient first
Phone contacts (name to number)HashMapFast lookup by key
Recently opened filesLinkedHashMap (access order)Easy LRU cache
Live vote counts from many threadsConcurrentHashMapThread-safe updates

Collection interface methods

  • These methods work on every List, Set, and Queue, because they come from the Collection interface.
MethodWhat it doesExample
add(e)Adds an element; returns false if a Set already has itbooks.add("Java")
addAll(c)Adds every element of another collectionbooks.addAll(newArrivals)
remove(o)Removes one matching elementbooks.remove("Java")
removeAll(c)Removes every element that is in cbooks.removeAll(damaged)
retainAll(c)Keeps only elements also in c (intersection)books.retainAll(requested)
removeIf(predicate)Removes elements matching a conditionbooks.removeIf(b -> b.isEmpty())
contains(o)Checks if an element existsbooks.contains("Java")
containsAll(c)Checks if all elements of c existbooks.containsAll(syllabus)
size()Number of elementsbooks.size()
isEmpty()True if no elementsbooks.isEmpty()
clear()Removes everythingbooks.clear()
iterator()Returns an Iterator for looping and safe removalbooks.iterator()
toArray()Copies elements into an arraybooks.toArray(new String[0])
stream()Creates a Stream for filter, map, collectbooks.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

MethodWhat it doesExample
put(k, v)Adds or replaces the value for a keycontacts.put("Asha", "98480")
get(k)Value for a key, or nullcontacts.get("Asha")
getOrDefault(k, d)Value or a default if missingstock.getOrDefault("pen", 0)
putIfAbsent(k, v)Adds only if the key is missingsettings.putIfAbsent("theme", "dark")
containsKey(k) / containsValue(v)Checks keys or valuescontacts.containsKey("Ravi")
remove(k)Removes the entry for a keycontacts.remove("Ravi")
merge(k, v, fn)Combines a new value with the old onecount.merge(word, 1, Integer::sum)
computeIfAbsent(k, fn)Creates a value when the key is missinggroups.computeIfAbsent(city, c -> new ArrayList<>())
keySet() / values() / entrySet()Views of keys, values, or entriesfor (var e : map.entrySet())
forEach((k, v) -> ...)Loops over every entrymap.forEach((k, v) -> print(k, v))
size() / isEmpty() / clear()Same meaning as in Collectioncontacts.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, Iterator when you must remove while looping, ListIterator to go backwards or replace, and forEach or 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 (List without <>) compile with warnings and fail at runtime with ClassCastException.
  • Use the diamond <> on the right side: new ArrayList<>(). Collections hold objects, so List<int> is not allowed; use List<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 the Collection interface.
MethodWhat it doesReal life
Collections.sort(list)Sorts in natural order (or with a Comparator)Arrange students by roll number
Collections.reverse(list)Reverses the orderShow latest messages first
Collections.shuffle(list)Random orderLucky draw, shuffle songs
Collections.max(c) / min(c)Largest or smallest elementTopper and lowest score
Collections.frequency(c, o)Counts occurrencesHow many times 100 was scored
Collections.binarySearch(list, key)Fast search in a sorted listFind a page in a sorted index
Collections.swap(list, i, j)Swaps two positionsSwap two players in a batting order
Collections.nCopies(n, o)Read-only list of n copiesPrint 3 cheers
Collections.unmodifiableList(list)Read-only viewShare a menu that customers cannot edit
Collections.synchronizedList(list)Thread-safe wrapperSimple shared list across threads
Collections.emptyList()Shared empty immutable listReturn "no results" safely
Collections.addAll(c, a, b, ...)Adds many elements at onceAdd 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 is Comparator.
PointComparableComparator
Packagejava.langjava.util
MethodcompareTo(T other)compare(T a, T b)
Where writtenInside the class being sortedSeparate class, lambda, or method reference
Number of ordersOne natural orderAny number of custom orders
Changes the class?Yes, the class implements itNo, works even on classes you cannot edit
Used byCollections.sort(list), TreeSet, TreeMap by defaultlist.sort(cmp), new TreeSet<>(cmp)
Examples in JDKString, Integer, LocalDateComparator.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 no null elements.
  • 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)
    }
}
L2

Advanced — Collections Overview

Complexity cheat sheet (amortized / average)

CollectionAddRemoveSearch / getNotes
ArrayListO(1) at end (amortized)O(n)get(i) O(1); contains O(n)Best default List
LinkedListO(1) at endsO(1) at ends; O(n) by valueO(n)Extra memory per node
HashSet / HashMapO(1)O(1)O(1)Needs good hashCode; worst case O(log n) with tree bins
LinkedHashSet / LinkedHashMapO(1)O(1)O(1)Keeps insertion or access order
TreeSet / TreeMapO(log n)O(log n)O(log n)Sorted; supports floor, ceiling, ranges
ArrayDequeO(1) at endsO(1) at endsO(n)Best Stack and Queue
PriorityQueueO(log n)poll O(log n)peek O(1)Heap, not fully sorted
ConcurrentHashMapO(1)O(1)O(1)Thread-safe without locking the whole map

How to choose the right collection

If you need...UseAvoid
An ordered list with index accessArrayListLinkedList (rarely faster)
No duplicates, fast lookupHashSetList.contains in a loop (O(n))
No duplicates in insertion orderLinkedHashSetSorting a HashSet output
Always sorted, range queriesTreeSet / TreeMapSorting a list after every insert
FIFO queue or LIFO stackArrayDequeStack and Vector (legacy, synchronized)
Process by priorityPriorityQueueSorting the whole list each time
Key to value lookupHashMapTwo parallel lists
Map in insertion order or an LRU cacheLinkedHashMapCustom linked structures
Shared map across threadsConcurrentHashMapHashtable, unsynchronized HashMap
Fixed constant dataList.of / Set.of / Map.ofMutable lists exposed publicly
Keys are enum constantsEnumMap / EnumSetHashMap with enum keys (slower)

equals and hashCode contract

  • HashSet, HashMap, and LinkedHash* use hashCode() to find the bucket and equals() to compare inside it.
  • Rule: if two objects are equal by equals, they must have the same hashCode. Always override both together, using the same fields.
  • Never change a field used in hashCode while the object is inside a HashSet or used as a HashMap key — the object gets "lost".
  • For TreeSet and TreeMap, compareTo (or the Comparator) decides equality, so keep it consistent with equals.
  • 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) throw ConcurrentModificationException if the collection is structurally changed during iteration, except through the iterator itself.
  • Fail-safe (weakly consistent or snapshot) iterators in java.util.concurrent never 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).
PointFail-fastFail-safe
ExamplesArrayList, HashMap, HashSet iteratorsCopyOnWriteArrayList, ConcurrentHashMap iterators
Change during loopThrows ConcurrentModificationExceptionNo exception
Works onThe original collectionA snapshot or a weakly consistent view
Sees new changes?Not applicable (it fails)Maybe not (snapshot may be old)
MemoryNo extra copyMay copy (copy-on-write)
Safe removaliterator.remove() or removeIfDirect 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 ArrayList or HashMap between threads that write can corrupt data.
OptionHow it worksUse when
Collections.synchronizedList/Map/SetWraps every method in a lockLow traffic; must still lock manually while iterating
Vector / HashtableLegacy classes with synchronized methodsOnly for old code
ConcurrentHashMapFine-grained locking and CAS; atomic merge, computeShared maps, counters, caches
CopyOnWriteArrayListCopies the array on every writeMany reads, very few writes (listeners)
ConcurrentLinkedQueueLock-free queueHigh-throughput producer-consumer without blocking
ArrayBlockingQueue / LinkedBlockingQueueput waits when full, take waits when emptyProducer-consumer pipelines
ConcurrentSkipListMapSorted, concurrent mapShared leaderboards and sorted data

Legacy collection classes

  • Before Java 1.2, Java had Vector, Stack, Hashtable, and Enumeration. They still work but are synchronized (slower) and have older APIs.
Legacy classProblemModern replacement
VectorEvery method synchronized, slowerArrayList (or CopyOnWriteArrayList)
StackExtends Vector, exposes index methodsArrayDeque with push / pop
HashtableLocks the whole table, no nullsHashMap or ConcurrentHashMap
EnumerationNo remove, long method namesIterator
PropertiesExtends HashtableStill fine for .properties config files

null handling across collections

Collectionnull elements / keysnull values (maps)
ArrayList, LinkedListAllowed (many)-
HashSet, LinkedHashSetOne null-
TreeSetNot allowed (natural order)-
ArrayDeque, PriorityQueueNot allowed-
HashMap, LinkedHashMapOne null keyAllowed
TreeMapNo null key (natural order)Allowed
Hashtable, ConcurrentHashMapNot allowedNot allowed
List.of, Set.of, Map.ofNot allowedNot allowed

Sequenced collections (Java 21)

  • Java 21 added SequencedCollection, SequencedSet, and SequencedMap for collections with a defined order.
  • New common methods: getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast(), and reversed(). Maps get firstEntry(), 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 Stream with stream(). Streams filter, transform, group, and summarise data in a readable pipeline.
  • Collectors.groupingBy, counting, summingInt, toMap, and joining turn 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

DoDo not
Declare with interfaces: List<String> list = new ArrayList<>()Declare as ArrayList<String> everywhere
Always use genericsUse raw types like List
Pick by need: List, Set, Queue, or MapUse ArrayList for everything
Override equals and hashCode together for keysUse mutable objects as map keys
Use removeIf or Iterator.remove to delete while loopingCall list.remove inside a for-each loop
Return empty collections, not nullForce callers to check for null
Use List.of / List.copyOf for read-only dataExpose internal mutable lists from getters
Set an initial capacity for very large lists or mapsLet a huge map resize again and again
Use concurrent collections for shared dataShare HashMap between writing threads
L3

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.

L4

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
    }
}
L5

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 ArrayDeque for both stacks and queues; avoid Stack, Vector, and Hashtable in new code.
  • Override equals and hashCode together, using the same fields, for objects stored in hash collections.
  • Delete while looping only with Iterator.remove() or removeIf.
  • List.of / Set.of / Map.of are immutable and reject null.
  • Loop maps with entrySet() to get the key and value in one step.
  • Measure before switching ArrayList to LinkedList; ArrayList wins in most real programs.
L6

Practice Programs List

  1. Store a playlist in a List, unique song names in a Set, and play counts in a Map from the same input.
  2. Show the difference between an array and an ArrayList by adding a fifth guest to both.
  3. Write a method that accepts Collection<String> and works for both a List and a Set.
  4. Print the same integers from a HashSet, a LinkedHashSet, and a TreeSet and compare the order.
  5. Use retainAll to find common subjects between two students.
  6. Build a phone book with HashMap using put, getOrDefault, putIfAbsent, and remove.
  7. Iterate a list in five different ways, including a ListIterator in reverse.
  8. Use Collections.max, frequency, shuffle, and reverse on a list of exam scores.
  9. Sort a list of products by price with Comparable and by rating with a Comparator.
  10. Create a Student class, add duplicates to a HashSet, then fix it with equals and hashCode.
  11. Trigger ConcurrentModificationException, then fix it with removeIf.
  12. Model a bank token queue with ArrayDeque and an emergency room with PriorityQueue.
  13. Build an LRU cache of the 3 most recently opened files using LinkedHashMap.
  14. Explain from memory which collections allow null and which do not.