Java LinkedList peekFirst() Method Example

The peekFirst() method of java.util.LinkedList class will return the first element of the list and will not remove the element from the list. This method performs the same operation as peek() method.


public E peekFirst() 

Retrieves the head (first element) of this list and will return null if the list is empty


The following example shows the usage of peekFirst() method.

import java.util.LinkedList;

public class PeekFirstMethodLinkedListExample {
	public static void main(String args[])
	// Create LinkedList object
        LinkedList list1 = new LinkedList();
        //adding elements to list1
        list1.add("String 1");
        list1.add("String 2");
        list1.add("String 3");
        list1.add("String 4");
        //Getting the head of the LinkedList
      	System.out.println("First element of the list is : "+list1.peekFirst());


First element of the list is : String 1

Leave a Reply

Your email address will not be published. Required fields are marked *