List.subList()
Returns the part of a list between two indexes.
Available since: Java 1.2
Syntax
List<E> subList(int fromIndex, int toIndex)Parameters
| Parameter | Type | Description |
|---|---|---|
| fromIndex | int | The start of the range (inclusive). |
| toIndex | int | The end of the range (exclusive). |
Return value
List<E>A view of part of the list, not a copy.
Examples
The first three elements and the rest:
void main() {
List<Integer> nums = List.of(10, 20, 30, 40, 50);
IO.println(nums.subList(0, 3));
IO.println(nums.subList(3, nums.size()));
}Output:
[10, 20, 30]
[40, 50]Changes to the part are visible in the original list:
void main() {
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));
nums.subList(1, 3).clear();
IO.println(nums);
}Output:
[1, 4, 5]Notes
The result is a window onto the original list: a change to one is visible in the other. If the size of the original list changes directly afterwards, using the window throws ConcurrentModificationException. For an independent copy use new ArrayList<>(list.subList(a, b)).
See also
- List.get() — Returns the list element at an index.
- Stream.limit() — Truncates a stream to its first N elements.
- Stream.skip() — Skips the first N elements of a stream.
Related recipes
In the tutorial
- Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.