Library contents

Java List.subList

Select a range using an inclusive start and exclusive end. A Java subList is a view backed by the original list.

A simple example

List.subList

  1. Start with A, B, C
  2. Do this Select the first two items
  3. Result A, B
The selected range ends before C.

Syntax

Java syntax
queue.subList(from, to)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Select two orders for the packing bench

A packing bench takes a small batch from the middle of the day's queue. The supervisor wants orders B and C on this bench while the other orders stay visible in the full queue.

From the programvar orders = List.of("A", "B", "C", "D")
ResultB, C
Main.java
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var orders = List.of("A", "B", "C", "D");
        System.out.println(String.join(", ", orders.subList(1, 3)));
    }
}
Output
B, C

Positions one and two are included. Position three is the boundary after the batch.

Advertisements

Remove a completed delivery batch

A delivery driver completes the first three drops on a manifest. Dispatch clears that range through the list view so the main manifest immediately shows only the remaining stop.

Result[D]
Main.java
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var drops = new ArrayList<>(List.of("A", "B", "C", "D"));
        drops.subList(0, 3).clear();
        System.out.println(drops);
    }
}
Output
[D]

Clearing the backed view removes the same entries from the original mutable list.

Prepare the next workshop roster

A teacher reads a workshop roster in arrival order. The coordinator prints the first two entries on a separate slip. Which entries appear, in order?

GivenMira · Ivo · Bea
Worked resultMira · Ivo

What to watch for

Structural changes to the backing list outside the view can invalidate it. Copy the view when it must outlive edits to the list.

Documentation for List.subList