Java Utility Library

Java LinkedList - peek() Method



The java.util.LinkedList.peek() method is used to retrieve the head (first element) of the list. Unlike the LinkedList poll method, it does not remove the retrieved element.

Syntax

public E peek()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the head (first element) of the list.

Exception

NA.

Example:

In the example below, the java.util.LinkedList.peek() method is used to retrieve the head of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedlist
    LinkedList<Integer> MyList = new LinkedList<Integer>();

    //populating linkedlist 
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);

    //printing linkedlist
    System.out.println("MyList contains: ");
    while(MyList.size() != 0) {
      System.out.println(MyList.peek());
      MyList.removeFirst();
   }
  }
}

The output of the above code will be:

MyList contains: 
10
20
30

❮ Java.util - LinkedList