Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Collections

Choosing a Java Collection: Immutable and Sequenced Collections

A key to look up? Each value once? A line? Otherwise a List. Then the locks: List.of and Map.of refuse Chai, an unmodifiable view follows its owner to [Latte, Mocha] while a copyOf snapshot stays at [Latte], and Java 21 adds getFirst, getLast and reversed.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Collections

What you will learn

  • Pick List, Set, Queue or Map by asking a few questions in order
  • Build fixed collections with List.of and Map.of and know what they refuse
  • Tell a read-only view from a copy made with List.copyOf
  • Use the Java 21 methods getFirst, getLast and reversed

Before you start

  • Java ArrayList
  • Java maps: HashMap, LinkedHashMap and TreeMap

Picking a collection is like picking a bag: a backpack, a suitcase or a wallet. Sometimes the bag also needs a lock so nothing inside can change. This lesson covers both choices.

Ask the questions from the top

Ask in order. A key to look things up? Yes: Map, for drink prices by name. Each value only once? Yes: Set, for a guest list. A line, first in first out? Yes: Queue with ArrayDeque, for orders waiting for pickup. None of these: List, for a menu shown in order. The first yes picks the collection. A key to look things up? Each value only once? A line, first in first out? None of these Map: drink prices by name Set: a guest list Queue (ArrayDeque): pickup orders List: a menu in order yes
The first yes picks the collection. When nothing fits, a List keeps order and allows repeats.
List<String> orders = new ArrayList<>();       // keeps order
orders.add("Latte");
orders.add("Mocha");
orders.add("Latte");                           // a repeat

Set<String> drinks = new TreeSet<>(orders);    // each once
Map<String, Integer> prices = new HashMap<>(); // by key
prices.put("Latte", 4);
Queue<String> pickup = new ArrayDeque<>(orders); // FIFO

System.out.println("List:  " + orders);
System.out.println("Set:   " + drinks);
System.out.println("Map:   " + prices.get("Latte"));
System.out.println("Queue: " + pickup.poll());
List:  [Latte, Mocha, Latte]
Set:   [Latte, Mocha]
Map:   4
Queue: Latte

A quick refresher: the list keeps the repeat and the order, the TreeSet drops the second Latte, the map finds 4 by key, and the queue's poll hands back the first order. A Queue has no index, so pickup.get(0) doesn't compile.

A menu that cannot change

List<String> menu = List.of("Latte", "Mocha");
Map<String, Integer> prices = Map.of("Latte", 4, "Mocha", 5);

System.out.println("Menu:  " + menu);
System.out.println("Mocha: " + prices.get("Mocha"));

try {
    menu.add("Chai");                    // refused
} catch (UnsupportedOperationException e) {
    System.out.println("add: " + e);
}
try {
    prices.put("Chai", 3);               // refused
} catch (UnsupportedOperationException e) {
    System.out.println("put: " + e);
}
Menu:  [Latte, Mocha]
Mocha: 5
add: java.lang.UnsupportedOperationException
put: java.lang.UnsupportedOperationException

One line builds each collection, and reading works as usual. But the lock goes on right away: add and put throw UnsupportedOperationException, and the menu stays the same. List.of doesn't accept null either; List.of("Latte", null) throws a NullPointerException.

A window, or a snapshot

List<String> orders = new ArrayList<>();
orders.add("Latte");

List<String> view = Collections.unmodifiableList(orders);
List<String> copy = List.copyOf(orders);

try {
    view.add("Chai");                    // callers: blocked
} catch (UnsupportedOperationException e) {
    System.out.println("Blocked: " + e);
}
System.out.println("Before: view " + view + ", copy " + copy);
orders.add("Mocha");                     // the owner adds
System.out.println("After:  view " + view + ", copy " + copy);
Blocked: java.lang.UnsupportedOperationException
Before: view [Latte], copy [Latte]
After:  view [Latte, Mocha], copy [Latte]

Say you pass a list to a method that shouldn't change it. Collections.unmodifiableList gives a view: a glass window on orders. You can look through it but not reach in, so view.add is blocked. List.copyOf gives a copy, a snapshot taken right now. The owner can still change orders; when it adds Mocha, the view shows it, while the copy still shows only Latte. The copy is locked too: copy.add("Chai") throws the same exception.

First, last and backwards (Java 21)

List<String> orders = List.of("Latte", "Mocha", "Chai");

// before Java 21
String lastOld = orders.get(orders.size() - 1);
System.out.println("Old way:  " + lastOld);

// Java 21 and later
System.out.println("First:    " + orders.getFirst());
System.out.println("Last:     " + orders.getLast());
System.out.println("Reversed: " + orders.reversed());
Old way:  Chai
First:    Latte
Last:     Chai
Reversed: [Chai, Mocha, Latte]

get(size() - 1) finds Chai, but it's clumsy. Since Java 21, getFirst and getLast read the two ends and reversed shows the same items backwards. This list comes from List.of, so it's still locked: orders.removeFirst() throws UnsupportedOperationException.

Locked, watched or open

List.of / copyOfunmodifiable viewArrayList
Can a caller add?nonoyes
After it's madenever changesfollows the ownerchanges when you edit it
Use it fora fixed menu, a snapshota read-only hand-outa list you must edit

That wraps up collections. Java 21 to 25 brought more changes like these; see what's new in Java 21 to 25.

Keep going in Java · 54 of 79

Previous
Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
Next post
Java Exception Handling: try, catch and finally
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java equals and hashCode: Why a HashSet Needs Both

== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.

From Arrays to Collections: The Java Collections Framework Map

An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.

Java Wrapper Classes and Autoboxing

List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.

Java ArrayList: The Stretchy Array

add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.

On this page

  • Ask the questions from the top
  • A menu that cannot change
  • A window, or a snapshot
  • First, last and backwards (Java 21)
  • Locked, watched or open
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.