Java LinkedList peek() Method Example

The getFirst() and element() method of java.util.LinkedList will get us the first element of the list. This peek() method will return the first element of the list and will not remove it from the list.

Signature

public E peek() 

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

Example

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

import java.util.LinkedList;

public class PeekMethodLinkedListExample {
	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.peek());
	}
}

Output

First element of the list is : String 1

Leave a Reply

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