How do I get the first and last elements of a List in Java?

You can use getFirst() and getLast() to read the first and last elements of a list without calculating their indexes.

In this example, you will read the first and last programming language names from a list.

Source code

Save the following code as FirstLastListExample.java:

import java.util.List;

public class FirstLastListExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "Kotlin");

        if (languages.isEmpty()) {
            IO.println("The list is empty.");
            return;
        }

        String firstLanguage = languages.getFirst();
        String lastLanguage = languages.getLast();

        IO.println("Languages: " + languages);
        IO.println("First language: " + firstLanguage);
        IO.println("Last language: " + lastLanguage);
    }
}

Explanation

The example creates a list containing three strings:

List<String> languages = List.of(
        "Java", "Python", "Kotlin");

A List maintains its elements in a defined order. Here, "Java" is the first element and "Kotlin" is the last.

Checking for an empty list

Before reading either element, the program checks whether the list is empty:

if (languages.isEmpty()) {
    IO.println("The list is empty.");
    return;
}

Both getFirst() and getLast() throw a NoSuchElementException when called on an empty list.

The return statement ends the method before either call can happen.

Reading the first element

Use getFirst() to retrieve the element at the beginning:

String firstLanguage = languages.getFirst();

For a nonempty list, this returns the same element as get(0).

Reading the last element

Use getLast() to retrieve the element at the end:

String lastLanguage = languages.getLast();

For a nonempty list, this returns the same element as:

languages.get(languages.size() - 1)

The named methods make the intent clear without requiring index calculations. Neither method removes an element or changes the list.

Run the example

Compile and run the file:

javac FirstLastListExample.java
java FirstLastListExample

Output

Languages: [Java, Python, Kotlin]
First language: Java
Last language: Kotlin

If you replace the list declaration with an empty list:

List<String> languages = List.of();

The output becomes:

The list is empty.

For a list containing only one element, getFirst() and getLast() return that same element.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.