Write a Java program to Get the first item from LinkedList collection using getFirst()


The code demonstrates how to use the getFirst method of LinkedList in Java to retrieve the first element from the list. In the Use_GetFirst 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 first element in the col list using the getFirst method. The getFirst method returns the first element in the list without removing it.

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

Source Code

import java.util.LinkedList;
public class Use_GetFirst
{
	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("First Element : " + col.getFirst());
	}
}

Output

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

Example Programs