Retrieve the last element from a LinkedList in Java


The last element of a Linked List can be retrieved using the method java.util.LinkedList.getLast() respectively. This method does not require any parameters and it returns the last element of the LinkedList.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Andy");
      l.add("Sara");
      l.add("James");
      l.add("Betty");
      l.add("Bruce");
      System.out.println("The last element of the Linked List is : " + l.getLast());
   }
}

Output

The last element of the Linked List is : Bruce

Now let us understand the above program.

The LinkedList l is created. LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.getLast() is used to retrieve the last element of the linked list. A code snippet which demonstrates this is as follows −

LinkedList<String> l = new LinkedList<String>();
l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");
System.out.println("The last element of the Linked List is : " + l.getLast());

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements