Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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.NoSuchElementException

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.