Write a Java program to Retrieve but not remove the elements of a LinkedList from both the ends


The code demonstrates how to retrieve elements from both ends of a LinkedList in Java. The Retrieve_BothEnds class contains a main method where a LinkedList object named list is created and populated with string elements using the add method.

The System.out.println statements are used to print the initial state of the list linked list. Then, the following methods are used to retrieve elements from the head (first) and tail (last) of the list linked list:

  • element(): Retrieves and removes the head (first) element of the list linked list. Throws NoSuchElementException if the list is empty.
  • getFirst(): Retrieves the head (first) element of the list linked list without removing it. Throws NoSuchElementException if the list is empty.
  • peek(): Retrieves but does not remove the head (first) element of the list linked list. Returns null if the list is empty.
  • peekFirst(): Retrieves but does not remove the head (first) element of the list linked list. Returns null if the list is empty.
  • peekLast(): Retrieves but does not remove the tail (last) element of the list linked list. Returns null if the list is empty.
  • getLast(): Retrieves the tail (last) element of the list linked list without removing it. Throws NoSuchElementException if the list is empty.

The System.out.println statements are used to print the retrieved elements from both ends of the list linked list.

As a result, the head and tail elements of the list linked list will be retrieved and printed, as demonstrated by the output of the System.out.println statements. Note that the peek() and peekFirst() methods will return null when the list is empty, whereas the other methods may throw NoSuchElementException in such cases.

Source Code

import java.util.*;
public class Retrieve_BothEnds
{
	public static void main(String[] args)
	{
		LinkedList<String> list = new LinkedList<String>();
		list.add("Apple"); 
		list.add("Mango");     
		list.add("Pineapple");  
		list.add("Cherry");    
		list.add("Guava");
		list.add("Banana");
		list.add("Watermelon"); 
		System.out.println(list);
 
		//Retrieving the elements from the head 
		System.out.println(list.element()); 
		System.out.println(list.getFirst());
		System.out.println(list.peek()); 
		System.out.println(list.peekFirst()); 
 
		//Retrieving the elements from the tail
		System.out.println(list.peekLast());    
		System.out.println(list.getLast()); 
	}
}

Output

[Apple, Mango, Pineapple, Cherry, Guava, Banana, Watermelon]
Apple
Apple
Apple
Apple
Watermelon
Watermelon

Example Programs