Java LinkedList peek() Method

Java LinkedList Java LinkedList


peek()The method is, in Java,LinkedLista very useful method provided by the class. It is used to retrieve but not remove the first element (head element) of the linked list. This method belongs toQueuethe operations of the interface,LinkedListand LinkedList implements this interface.

Method syntax:

public E peek()

Return value:

  • If the linked list is not empty, returns the first element of the linked list
  • If the linked list is empty, returns nullnull

Method Features

Non-destructive operation

peek()The method only "views" the first element of the linked list without removing it. This is different frompoll()orremove()the remove() method, which removes the element.

Null safety

When the linked list is empty,peek()peek() returns nullnulland does not throw an exception, which makes it moregetFirst()orelement()safer than element() in some scenarios.

Time complexity

SinceLinkedListLinkedList is implemented based on a doubly linked list,peek()the time complexity of the method is O(1), because it only needs to access the head node.


Usage examples

Basic example

Example

import java.util.LinkedList;

public class PeekExample {
    public static void main(String[] args) {
        LinkedList<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
       
        // Use peek() to view the first element
        String firstFruit = fruits.peek();
        System.out.println("First fruit: " + firstFruit);  // Output: First fruit: Apple
        System.out.println("LinkedList after peek(): " + fruits);  // Output: [Apple, Banana, Cherry]
    }
}

Empty linked list example

Example

import java.util.LinkedList;

public class EmptyListPeek {
    public static void main(String[] args) {
        LinkedList<Integer> numbers = new LinkedList<>();
       
        Integer firstNumber = numbers.peek();
        System.out.println("First number: " + firstNumber);  // Output: First number: null
    }
}

Comparison with other similar methods

peek() vs getFirst()

Method Behavior on empty linked list Throws exception
peek() Returns null no
getFirst() Throws NoSuchElementException Yes

4.2 peek() vs element()

Method Behavior on empty linked list Throws exception
peek() Returns null no
element() Throws NoSuchElementException Yes

4.3 peek() vs poll()

Method Whether it removes elements Behavior on empty linked list
peek() no Returns null
poll() Yes Returns null

Practical application scenarios

Message queue processing

When processing a message queue, we often need to view the message at the head of the queue without removing it:

Example

LinkedList<Message> messageQueue = new LinkedList<>();
// ... add messages to the queue

// Check but do not remove the first message
Message nextMessage = messageQueue.peek();
if (nextMessage != null && nextMessage.isHighPriority()) {
    // Process high-priority messages
}

Task scheduling system

In a task scheduling system,peek()peek() can be used to check the next task to execute:

Example

LinkedList<Task> taskQueue = new LinkedList<>();
// ... add tasks to the queue

Task nextTask = taskQueue.peek();
if (nextTask != null && nextTask.isReadyToExecute()) {
    // Execute the task
}

Browser history

Simulate viewing the most recently visited page in a browser without removing it from history:

Example

LinkedList<String> browserHistory = new LinkedList<>();
// ... add visit records

String lastVisited = browserHistory.peek();
System.out.println("Most recently visited page: " + lastVisited);

Notes

  1. Null value handling: Sincepeek()peek() may return nullnull, you should perform a null check before using the return value to avoidNullPointerException。

  2. Concurrent environment:LinkedListLinkedList is not thread-safe. If it is used in a multi-threaded environment,peek(), additional synchronization measures are required.

  3. Performance considerations: Althoughpeek()the operation itself is O(1), if it is called frequently along with other operations, you may need to consider more efficient data structures.

  4. Comparison with stack operations: WhenLinkedListLinkedList is used as a stack,peek()peek() views the first element (top of the stack), which is the same asStackthe Stack class'speek()peek() method behavior.

Java LinkedList Java LinkedList

Other extensions