Study guide

6.3 Core Collections: Lists, Sets, Queues, and Maps

Oracle Java SE 21 Developer 1Z0-830

Track your progress as you read

Finished sections get a check mark.

1 Chapter 1: Java Basics, Primitive Types, and Operators

1.1 Program Structure, Primitives, Literals, Scopes, and var 1.2 Operators, Precedence, and Type Casting 1.3 Strings, Text Blocks, and StringBuilder 1.4 Date and Time APIs (java.time)

2 Chapter 2: Controlling Program Flow & Pattern Matching

2.1 Conditional Logic: if-else and Ternary Operators 2.2 Switch Statements and Switch Expressions 2.3 Pattern Matching for switch and instanceof 2.4 Loops and Branching Statements

3 Chapter 3: Object-Oriented Design & Class Architecture

3.1 Class Declarations, Constructors, and Object Lifecycle 3.2 Encapsulation and Access Modifiers 3.3 Inheritance, Method Overriding, and Polymorphism 3.4 Abstract Classes and Interfaces 3.5 Nested, Inner, Local, and Anonymous Classes 3.6 Method Overloading, Overload Resolution, and Varargs

4 Chapter 4: Modern Java Data Modeling: Records, Enums, and Sealed Types

4.1 Java Records, Canonical/Compact Constructors, and Component Accessors 4.2 Java Enums: Fields, Methods, and Abstract Constant-Specific Behavior 4.3 Sealed Classes and Interfaces: permits, final, non-sealed, and Hierarchy Architecture 4.4 Advanced Record Patterns (JEP 440), Nested Deconstruction, and Sealed Hierarchy Exhaustiveness

5 Chapter 5: Exception Handling and Annotations

5.1 Exception Hierarchy: Checked vs. Unchecked Exceptions 5.2 Exception Handling: try, catch, finally, and Multi-Catch 5.3 Resource Management: try-with-resources and AutoCloseable 5.4 Custom Exceptions and Best Practices 5.5 Java Annotations: Built-in, Meta-Annotations, and Custom Types

6 Chapter 6: Generics and the Collections Framework

6.1 Generics Fundamentals and Generic Methods 6.2 Wildcards, Type Bounds, and Type Erasure 6.3 Core Collections: Lists, Sets, Queues, and Maps 6.4 Sequenced Collections in Java 21 6.5 Sorting, Comparable, and Comparator 6.6 Arrays: Creation, Multidimensional Forms, and the Arrays Utility Class

7 Chapter 7: Functional Programming & Lambda Expressions

7.1 Built-in Functional Interfaces in java.util.function 7.2 Lambda Expressions, Variable Scopes, and Effectively Final 7.3 Method References: Four Varieties and Edge Cases 7.4 Working with java.util.Optional

8 Chapter 8: The Stream API and Data Pipelines

8.1 Stream Creation and Intermediate Operations 8.2 Terminal Operations and Reductions 8.3 Advanced Collectors, Grouping, Partitioning, and Teeing 8.4 Primitive Streams and Parallel Stream Processing

9 Chapter 9: Concurrency, Multithreading, and Virtual Threads

9.1 Thread Fundamentals, Creation, and Lifecycle 9.2 Thread Safety, Synchronization, and the Java Memory Model 9.3 Concurrency Utilities: ExecutorService, Callable, and Future 9.4 Concurrent Collections, Atomics, and Explicit Locks 9.5 Virtual Threads in Java 21 (Carrier Threads, Pinning, and Best Practices)

10 Chapter 10: The Java Platform Module System (JPMS)

10.1 Module Architecture and module-info.java Declarations 10.2 Module Directives: requires, exports, opens, provides, and uses 10.3 Modular Compilation, Packaging, and CLI Execution 10.4 Module Types, Migration Strategies, ServiceLoader SPI, and JLink

11 Chapter 11: Java I/O, NIO.2, and Object Serialization

11.1 Classic Java I/O Streams and Readers/Writers 11.2 Java NIO.2 File API: Path, Paths, and File System Operations 11.3 Advanced NIO.2 Stream Operations and Directory Traversal 11.4 Java Object Serialization and Record Serialization

12 Chapter 12: Implementing Localization and Internationalization

12.1 Locales and Resource Bundles 12.2 Formatting and Parsing Numbers, Currencies, Dates, Times, and Messages

6.3 Core Collections: Lists, Sets, Queues, and Maps

Key Takeaways Explain This Topic AI

The Java Collections Framework organizes collections under Iterable<T> and Collection<E>, while Map<K, V> forms an independent root hierarchy.

ArrayList provides O(1) indexed random access with a 1.5x dynamic growth factor, while LinkedList offers O(1) endpoint insertion/removal without RandomAccess support.

Set implementations enforce uniqueness: HashSet relies on hashCode/equals, LinkedHashSet preserves encounter order, and TreeSet maintains sorted order via Comparable/Comparator.

ArrayDeque provides faster, memory-efficient LIFO/FIFO operations than Stack or LinkedList and strictly rejects null elements.

Unmodifiable factory methods (List.of, Set.of, Map.of) create truly immutable, null-hostile collections, differing fundamentally from unmodifiable view wrappers.

Last updated: September 2026

Core Collections: Lists, Sets, Queues, and Maps

The Java Collections Framework (JCF) provides a unified architecture for representing, organizing, and manipulating data collections. On the Oracle Certified Professional: Java SE 21 Developer (1Z0-830) exam, questions assess your in-depth understanding of collection internal architectures, performance trade-offs, null acceptance rules, unmodifiable factories, and functional Map mutation operations.

1. JCF Architecture and Root Interfaces

The framework is structured into two main inheritance branches:

java.lang.Iterable<T> → \rightarrow → java.util.Collection<E> : The root hierarchy for element-based collections ( List , Set , Queue , Deque ).

java.util.Map<K, V> : An independent root hierarchy representing key-value mappings (does not extend Collection or Iterable ).

2. The List<E> Implementations: ArrayList vs. LinkedList

A List is an ordered collection (sequence) that permits duplicate elements and allows precise control over element insertion by integer index. package java.util;

  • public interface List<E> extends Collection<E> {
  • E get(int index);
  • E set(int index, E element);
  • void add(int index, E element);
  • E remove(int index);
  • int indexOf(Object o);
  • List<E> subList(int fromIndex, int toIndex);
  • }
  • ArrayList<E>

Underlying Data Structure : Dynamic resizable array ( Object[] elementData ).

Initial Capacity : Default capacity is 10 10 10 upon first element addition.

Growth Formula : Grows by 50 % 50\% 50% ( 1.5 × 1.5\times 1.5 × ) when capacity is exceeded: newCapacity = oldCapacity + ( oldCapacity ≫ 1 ) \text{newCapacity} = \text{oldCapacity} + (\text{oldCapacity} \gg 1) newCapacity = oldCapacity + ( oldCapacity ≫ 1 )

Time Complexities :

O ( 1 ) O(1) O ( 1 ) random access ( get(i) , set(i, val) ). Implements the RandomAccess marker interface.

Amortized O ( 1 ) O(1) O ( 1 ) append ( add(val) ).

O ( n ) O(n) O ( n ) insertion or removal at arbitrary positions due to System.arraycopy element shifting.

Null Support : Fully permits null elements.

LinkedList<E>

Underlying Data Structure : Doubly-linked node chain ( Node<E> with item , next , prev ).

Dual Interface Implementation : Implements both List<E> and Deque<E> .

Time Complexities :

O ( 1 ) O(1) O ( 1 ) insertion and removal at head and tail.

O ( n ) O(n) O ( n ) indexed lookup ( get(i) traverses from nearest end). Does not implement RandomAccess .

Memory Overhead : Higher memory footprint per element due to node object allocation and bidirectional pointers.

3. The Set<E> Implementations: HashSet , LinkedHashSet , and TreeSet

A Set is a Collection that contains no duplicate elements ( e 1 . equals ( e 2 ) e_1.\text{equals}(e_2) e 1 ​ . equals ( e 2 ​ ) is never true). // Set implementations compared

  • Set<String> hashSet = new HashSet<>(); // Fast, no ordering guarantee
  • Set<String> linkedSet = new LinkedHashSet<>(); // Fast, maintains insertion encounter order
  • Set<String> treeSet = new TreeSet<>(); // Logarithmic, sorted by natural order or Comparator
  • 1. HashSet<E>

Backed internally by a HashMap<E, Object> .

O ( 1 ) O(1) O ( 1 ) average time for add , remove , and contains .

Requires stored elements to correctly implement consistent hashCode() and equals() contracts.

Order : Makes no guarantees regarding iteration order; order can change across JVM executions or table rehashes.

2. LinkedHashSet<E>

Extends HashSet<E> while maintaining a doubly-linked list running through all entries.

Iteration occurs in insertion encounter order .

Performance is nearly equal to HashSet , with slightly faster iteration proportional to set size rather than capacity .

3. TreeSet<E>

Backed by a Red-Black self-balancing binary search tree ( NavigableMap<E, Object> ).

O ( log ⁡ n ) O(\log n) O ( lo g n ) time for add , remove , and contains .

Elements are ordered according to their natural ordering ( Comparable ) or an explicit Comparator .

Uniqueness Contract : Uniqueness is determined strictly by compareTo() or compare() returning 0 , not by equals() !

Null Handling : Throws NullPointerException if null is added when using natural ordering.

4. The Queue<E> and Deque<E> Implementations

Queues represent collections designed for holding elements prior to processing, typically in FIFO (First-In, First-Out) or priority order. Deque (Double-Ended Queue) supports element insertion and removal at both endpoints (LIFO and FIFO).

Queue Method Matrix: Exception vs. Special Value

  • Operation Type Throws Exception on Failure Returns Special Value ( false / null )
  • Insert add(e) (throws IllegalStateException ) offer(e) (returns false if full)
  • Remove remove() (throws NoSuchElementException ) poll() (returns null if empty)
  • Examine element() (throws NoSuchElementException ) peek() (returns null if empty)
  • ArrayDeque<E> vs. LinkedList<E> vs. Legacy Stack

ArrayDeque uses a resizable circular array buffer.

Significantly faster than LinkedList for queue and stack operations due to memory locality and lack of node allocations.

Preferred over the legacy synchronized java.util.Stack .

Strict Null Rule : ArrayDeque strictly prohibits null elements , throwing NullPointerException on add(null) or offer(null) .

PriorityQueue<E>

Implements an unbounded priority min-heap.

Elements are ordered according to natural order or a custom Comparator .

peek() and poll() always return the lowest (highest priority) element in O ( log ⁡ n ) O(\log n) O ( lo g n ) time.

Iteration Order : Iterating with for-each or iterator() does NOT guarantee sorted order (only root min-heap property is guaranteed).

Null Rule : Strictly prohibits null elements (throws NullPointerException ).

5. The Map<K, V> Implementations

Map maps unique keys to values. Keys cannot contain duplicates, and each key maps to at most one value.

HashMap<K, V> Internals & Treeification

Bucket Table : Array of Node<K, V> buckets.

Default Settings : Initial capacity = 16 16 16 , load factor = 0.75 0.75 0.75 . Threshold to resize = 16 × 0.75 = 12 16 \times 0.75 = 12 16 × 0.75 = 12 .

Treeification (Java 8+) : When collisions in a single bucket reach TREEIFY_THRESHOLD = 8 and total table capacity is at least 64 64 64 , the bucket linked list is converted to a Red-Black tree ( TreeNode ), reducing worst-case lookup from O ( n ) O(n) O ( n ) to O ( log ⁡ n ) O(\log n) O ( lo g n ) .

If capacity is < 64 < 64 < 64 , the table resizes instead of treeifying.

When bucket entries shrink to UNTREEIFY_THRESHOLD = 6 during resizing, the tree is converted back into a linked list.

LinkedHashMap<K, V>

Maintains a doubly-linked list through all entries.

Can maintain insertion order (default) or access order (for LRU caches when constructed with new LinkedHashMap<>(cap, factor, true) ).

TreeMap<K, V>

Implements NavigableMap<K, V> using a Red-Black tree.

Keys are sorted. Rejects null keys when using natural ordering.

6. Null Acceptance Rules Across All Collections

Understanding null support across collections is one of the most frequently tested topics on the 1Z0-830 exam:

  • Collection / Map Null Elements / Keys Null Values Notes
  • ArrayList , LinkedList Allowed N/A Allows multiple nulls
  • HashSet , LinkedHashSet Allowed (1 null) N/A At most one null
  • TreeSet Prohibited N/A Throws NullPointerException (natural order)
  • ArrayDeque , PriorityQueue Prohibited N/A Throws NullPointerException
  • HashMap , LinkedHashMap Allowed (1 null key) Allowed Null key placed in bucket 0
  • TreeMap Prohibited (key) Allowed Throws NPE for null key (natural order)
  • Hashtable , ConcurrentHashMap Prohibited (key) Prohibited Throws NPE for null key or value
  • List.of , Set.of , Map.of Prohibited Prohibited Null-hostile: Throws NPE
  • 7. Modern Map Functional Computation Methods

Java 8 introduced default methods on Map to perform atomic, concise key-value transformations: Map<String, Integer> wordCounts = new HashMap<>();

  • // 1. getOrDefault: Returns fallback if key is absent
  • int count = wordCounts.getOrDefault("java", 0);
  • // 2. putIfAbsent: Inserts only if key is missing or mapped to null
  • wordCounts.putIfAbsent("java", 1);
  • // 3. computeIfAbsent: Computes value ONLY if key is absent or mapped to null
  • wordCounts.computeIfAbsent("python", key -> key.length()); // "python" -> 6

// 4. computeIfPresent: Recomputes ONLY if key is present and non-null

// If remapping function returns null, the entry is REMOVED from the map!

wordCounts.computeIfPresent("java", (k, v) -> v + 1); // "java" -> 2

wordCounts.computeIfPresent("python", (k, v) -> null); // REMOVES "python"!

  • // 5. compute: Computes new value regardless of presence
  • // If function returns null, existing entry is REMOVED
  • wordCounts.compute("ruby", (k, v) -> (v == null) ? 1 : v + 1);

// 6. merge: Essential for frequency counting / combining values

// If key absent -> sets value. If present -> applies remapping function.

// If remapping function returns null -> REMOVES entry!

  • wordCounts.merge("java", 10, (oldVal, newVal) -> oldVal + newVal); // 2 + 10 = 12
  • wordCounts.merge("scala", 5, Integer::sum); // "scala" absent -> sets to 5

Important

Map Removal on Null : In compute , computeIfPresent , and merge , if the remapping lambda returns null , the key is removed from the map completely!

8. Unmodifiable Collection Factories vs. View Wrappers

Java 9 introduced convenient unmodifiable collection factory methods: List<String> list = List.of("A", "B", "C");

  • Set<String> set = Set.of("X", "Y", "Z");
  • Map<String, Integer> map = Map.of("K1", 1, "K2", 2);
  • Map<String, Integer> bigMap = Map.ofEntries(
  • Map.entry("A", 1),
  • Map.entry("B", 2)
  • );

Characteristics of List.of , Set.of , Map.of :

Truly Immutable : Calling mutating methods ( add , remove , set , put ) throws UnsupportedOperationException .

Null-Hostile : Passing null elements or keys/values throws NullPointerException immediately.

Duplicate-Hostile at Creation : Set.of("A", "A") or Map.of("K", 1, "K", 2) throws IllegalArgumentException at construction time!

Randomized Iteration Order : Set.of and Map.of randomize iteration order across JVM runs to prevent reliance on order.

Space-Efficient : Highly optimized internal representations consuming significantly less memory than ArrayList or HashSet .

Factories vs. Collections.unmodifiableList() Views

Collections.unmodifiableList(existingList) : Creates an unmodifiable wrapper view around an existing collection. If the underlying existingList is mutated directly, the changes are visible through the unmodifiable view.

List.copyOf(existingList) (Java 10+): Creates a true independent unmodifiable copy. If existingList is already an unmodifiable collection created by List.of() , copyOf returns the original instance directly without copying.

9. Concurrent Collections Overview

Standard collections are not thread-safe. Java provides specialized concurrent implementations in java.util.concurrent :

ConcurrentHashMap<K, V> : Uses lock-striping and CAS (Compare-And-Swap) at the bucket node level. Allows concurrent reads without locking and highly concurrent writes. Rejects null keys and values.

CopyOnWriteArrayList<E> : Thread-safe variant of ArrayList where all mutative operations ( add , set , remove ) are implemented by making a fresh copy of the underlying array. Iterators never throw ConcurrentModificationException and reflect the snapshot at the time the iterator was created. Ideal for read-heavy, write-rare scenarios (e.g., event listeners).

Loading diagram... Java Collections Framework Core Class and Interface Hierarchy