Write a Java program to Get the last item from the LinkedList without removing it


The code demonstrates how to use the peekLast method of LinkedList in Java to retrieve the last item from the list without removing it.

In the GetLast_Item class, a LinkedList object named list is created without specifying a type parameter, allowing it to hold items of any type. Several items of different types, including 18, "JAVA", 54.78, 'J', and true, are added to the list using the add method.

The System.out.println statements are used to print the items in the list and the last item in the list using the peekLast method. The peekLast method retrieves the last item from the list without removing it, and returns null if the list is empty.

Note that peekLast does not modify the list, so the list remains unchanged after calling peekLast. If you want to retrieve and remove the last item from the list, you can use the pollLast method instead. Also, keep in mind that peekLast has a time complexity of O(1) as it operates on the tail of the list.

Source Code

import java.util.LinkedList;
public class GetLast_Item
{
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.add(18);
		list.add("JAVA");
		list.add(54.78);
		list.add('J');
		list.add(true);
 
		System.out.println("LinkedList Items : " + list);
		System.out.println("Last Item : " + list.peekLast());
	}
}

Output

LinkedList Items : [18, JAVA, 54.78, J, true]
Last Item : true

Example Programs