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


The code demonstrates how to use the peek and peekFirst methods of LinkedList in Java to retrieve the head (first) item from the list without removing it.

  • In the GetHead_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 head item (first item) in the list using the peek and peekFirst methods. Both peek and peekFirst methods retrieve the head item from the list without removing it, and return null if the list is empty.
  • Note that peek and peekFirst do not modify the list, so the list remains unchanged after calling them. If you want to retrieve and remove the head item from the list, you can use the poll or pollFirst methods instead. Also, keep in mind that peek and peekFirst have a time complexity of O(1) as they operate on the head of the list.

Source Code

import java.util.LinkedList;
public class GetHead_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("Head Item : " + list.peek());
		System.out.println("Head Item : " + list.peekFirst());
	}
}

Output

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

Example Programs