SupportWriter space ↗
← Back to the journal
Core API

How do I get the first and the last element of a LinkedList?

The get the first element we can use the LinkedList.getFirst() method and to get the last element we can use the LinkedList.getLast() method. package org.kodejava.util; import java.util.LinkedList; public class LinkedListGetFirstLast { public static void main(String[] args) { LinkedList<String> names = new LinkedList<>(); names.add("Alice"); names.add("Bob"); names.add("Carol"); names.add("Mallory"); // Get the first and the last element of […]

DWayan · 16 Nov 2009 · 1 min read

Article by Wayan · Source: Kode Java ↗

The get the first element we can use the LinkedList.getFirst() method and to get the last element we can use the LinkedList.getLast() method.

package org.kodejava.util;

import java.util.LinkedList;

public class LinkedListGetFirstLast {
    public static void main(String[] args) {
        LinkedList<String> names = new LinkedList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");

        // Get the first and the last element of the linked list
        String first = names.getFirst();
        String last = names.getLast();

        System.out.println("First member = " + first);
        System.out.println("Last member  = " + last);
    }
}

The program will print the following result:

First member = Alice
Last member  = Mallory
← Explore more notes