Retrieve the last element from a LinkedList in Java

Java 8Object Oriented ProgrammingProgramming

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());
raja
Published on 30-Jan-2019 07:59:05
Advertisements