Write a Java program to retrieve but does not remove, the last element of a linked list


The Java code provided demonstrates how to use the peekLast() method in a linked list to retrieve the last element without removing it.

  • The code defines a class named Retrieve_NotRemove with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a new LinkedList object named fru_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Guava", "Papaya", "Mulberry", etc., are added to the fru_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the initial contents of the fru_list before any modifications.
  • The peekLast() method is called on the fru_list to retrieve the last element in the list without removing it. The value of the last element is stored in a variable x.
  • The System.out.println statement is used to print the last element retrieved from the fru_list using the peekLast() method.
  • Finally, the System.out.println statement is used to print the original contents of the fru_list after the peekLast() method is called, which confirms that the original list remains unchanged.
  • The output of the program will be the initial contents of the fru_list printed on the first line, followed by the last element retrieved from the list, and then the original contents of the fru_list printed again.

Source Code

import java.util.*;
public class Retrieve_NotRemove
{
	public static void main(String[] args)
	{
		LinkedList <String> fru_list = new LinkedList <String> ();
		fru_list.add("Guava");
		fru_list.add("Papaya");
		fru_list.add("Mulberry");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon");
		fru_list.add("Pineapple");
		System.out.println("Given Linked List : " + fru_list);
		String x = fru_list.peekLast();
		System.out.println("Last Element in the List : " + x);
		System.out.println("Original Linked List : " + fru_list);
	}
}

Output

Given Linked List : [Guava, Papaya, Mulberry, Apple, Banana, Cherry, Watermelon, Pineapple]
Last Element in the List : Pineapple
Original Linked List : [Guava, Papaya, Mulberry, Apple, Banana, Cherry, Watermelon, Pineapple]

Example Programs