List.getFirst()
Returns the first or the last element of an ordered collection.
Available since: Java 21
Syntax
default E getFirst()
default E getLast()Return value
EThe first (or the last) element.
Examples
The first and the last element without indexes:
void main() {
List<String> queue = new ArrayList<>(List.of("Anna", "Oleg", "Ivan"));
IO.println(queue.getFirst());
IO.println(queue.getLast());
queue.removeFirst();
IO.println(queue);
}Output:
Anna
Ivan
[Oleg, Ivan]An empty list throws an exception:
void main() {
try {
new ArrayList<String>().getFirst();
} catch (NoSuchElementException e) {
IO.println(e);
}
}Output:
java.util.NoSuchElementExceptionNotes
The methods come from the SequencedCollection interface (Java 21) and exist on List, Deque, LinkedHashSet and TreeSet. The same interface declares addFirst(), addLast(), removeFirst() and removeLast(). An empty collection throws NoSuchElementException, so check isEmpty() first.
See also
- List.get() — Returns the list element at an index.
- List.reversed() — Returns the list in reverse order without copying it.
- List.isEmpty() — Checks whether a list is empty.
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.