How to get the first and last element of a list
Short answer
Since Java 21 lists have getFirst() and getLast():
void main() {
var queue = List.of("Anna", "Oleg", "Boris");
IO.println(queue.getFirst());
IO.println(queue.getLast());
}Output:
Anna
BorisBy index
In older Java versions use get(0) and get(size() - 1):
void main() {
var queue = List.of("Anna", "Oleg", "Boris");
IO.println(queue.get(0));
IO.println(queue.get(queue.size() - 1));
}Output:
Anna
BorisRemoving the first or last
removeFirst() and removeLast() remove and return the end elements:
void main() {
var stack = new ArrayList<>(List.of(1, 2, 3));
IO.println(stack.removeLast());
IO.println(stack);
}Output:
3
[1, 2]Safe for an empty list
A stream with findFirst() returns an Optional and does not fail on an empty list:
void main() {
List<String> empty = List.of();
IO.println(empty.stream().findFirst().orElse("nobody"));
}Output:
nobodyCommon mistake
Calling getFirst() on an empty list:
void main() {
List<String> names = new ArrayList<>();
IO.println(names.getFirst());
}Output:
Exception in thread "main" java.util.NoSuchElementExceptionCheck isEmpty() before the call.
Functions used in this recipe
- List.getFirst() — Returns the first or the last element of an ordered collection.
- List.get() — Returns the list element at an index.