Write a Java program to Get the last item from LinkedList collection using getLast()


The code demonstrates how to use the getLast method of LinkedList in Java to retrieve the last element from the list. In the Use_GetLast class, a LinkedList object named col is created with a type parameter specified as String, indicating that it can only hold items of type String. Several color names, including "Pink", "Yellow", "Green", "Orange", "Red", and "Blue", are added to the col using the add method.

The System.out.println statements are used to print the color names in the col list and the last element in the col list using the getLast method. The getLast method returns the last element in the list without removing it.

After retrieving the last element using getLast, the last element is printed using the System.out.println statement. Note that getLast throws a NoSuchElementException if the list is empty. Therefore, it's important to check if the list is empty before calling getLast to avoid runtime exceptions.

Source Code

import java.util.LinkedList;
public class Use_GetLast
{
	public static void main(String[] args)
	{
		LinkedList <String> col = new LinkedList <String>();
		col.add("Pink");
		col.add("Yellow");
		col.add("Green");
		col.add("Orange");
		col.add("Red");
		col.add("Blue");
 
		System.out.println("Color Names : " + col);
		System.out.println("Last Element : " + col.getLast());
	}
}

Output

Color Names : [Pink, Yellow, Green, Orange, Red, Blue]
Last Element : Blue

Example Programs