Java LinkedList peek()
method
The peek()
method in Java's LinkedList
class allows you to examine the first element of the list without removing it. Think of it as a quick glance at what’s at the front, similar to looking at the next card in a deck before deciding whether to play it.
Syntax
public E peek()
Description
The peek()
method retrieves, but does not remove, the first element of this list. It returns null
if the list is empty.
Parameters
Parameter | Description |
---|---|
None | This method does not take any parameters. |
Return Value
The peek()
method returns the first element of the list (the head) or null
if the list is empty.
Examples
Example 1: Peeking at an Empty List
This example demonstrates what happens when you try to peek at a list that contains no elements.
import java.util.LinkedList;
public class PeekExample1 {
public static void main(String[] args) {
LinkedList<String> myList = new LinkedList<>();
String firstElement = myList.peek();
System.out.println("First element: " + firstElement); // Output will be null
}
}
First element: null
In this case, because the list myList
is empty, peek()
returns null
. This is important to handle in your code – always check for null
before trying to use the returned value.
Example 2: Peeking at a List with Elements
This example shows how to peek at the first element of a list that does contain elements.
import java.util.LinkedList;
public class PeekExample2 {
public static void main(String[] args) {
LinkedList<Integer> myList = new LinkedList<>();
myList.add(10);
myList.add(20);
myList.add(30);
Integer firstElement = myList.peek();
System.out.println("First element: " + firstElement); // Output will be 10
}
}
First element: 10
Here, the list contains three integers. The peek()
method returns 10, which is the first element added to the list. Crucially, the list itself remains unchanged – the '10' hasn’t been removed.
Example 3: Using peek() with a List of Strings
This example demonstrates peeking at a list containing strings.
import java.util.LinkedList;
public class PeekExample3 {
public static void main(String[] args) {
LinkedList<String> myList = new LinkedList<>();
myList.add("apple");
myList.add("banana");
myList.add("cherry");
String firstElement = myList.peek();
System.out.println("First element: " + firstElement); // Output will be apple
}
}
First element: apple
This example works similarly to the previous one, but using strings instead of integers. peek()
retrieves “apple” without modifying the list.