Java LinkedList peek() Method
Example
Look at the first item in a list, before and after items are added:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
System.out.println(cars.peek());
cars.add("Volvo");
cars.add("BMW");
System.out.println(cars.peek());
}
}
Definition and Usage
The peek() method returns the first item in the list. It does not remove the item.
If the list is empty, peek() returns null (no value). This is the difference from element() and getFirst(), which throw an exception when the list is empty.
Tip: Use the poll() method to get the first item and also remove it from the list.
Syntax
public T peek()
T refers to the data type of items in the list.
Parameter Values
None.
Technical Details
| Returns: | The first item in the list, or null if the list is empty. |
|---|
Related Pages
❮ LinkedList Methods