Java LinkedList getFirst() Method Example

The getFirst() method of java.util.LinkedList will get us the first element of the list. This method does the same functionality of element() method of LinkedList.


public E getFirst() 

Retrieves the first element of the list. Throws “NoSuchElementException” if the list is empty.


The following example shows the usage of getFirst() 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());


First element of the list is : Element1

Leave a Reply

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