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
- Start with A, B, C
- Do this Select the first two items
- Result A, B
Syntax
queue.subList(from, to)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSelect 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.
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)));
}
}
B, C
Positions one and two are included. Position three is the boundary after the batch.
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.
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);
}
}
[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?
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.