Get first and last elements from Java LinkedList

Java 8Object Oriented ProgrammingProgramming

The first and last elements of a Linked List can be obtained using the methods java.util.LinkedList.getFirst() and java.util.LinkedList.getLast() respectively. Neither of these methods require any parameters.

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 l = new LinkedList();
      l.add("John");
      l.add("Sara");
      l.add("Susan");
      l.add("Betty");
      l.add("Nathan");
      System.out.println("The first element of the Linked List is : " + l.getFirst());
      System.out.println("The last element of the Linked List is : " + l.getLast());
   }
}

The output of the above program is as follows

The first element of the Linked List is : John
The last element of the Linked List is : Nathan

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.getFirst() and LinkedList.getLast() are used to get the first and last elements of the linked list respectively. A code snippet which demonstrates this is as follows

LinkedList l = new LinkedList();
l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");
System.out.println("The first element of the Linked List is : " + l.getFirst());
System.out.println("The last element of the Linked List is : " + l.getLast());
raja
Published on 17-Jan-2019 08:11:53
Advertisements