Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java LinkedList peek() Method

Java LinkedList peek() Method

Java LinkedList Java LinkedList


peek() The method is in Java's LinkedList is a very useful method provided by the class; it retrieves but does not remove the first element (head element) of the list. This method belongs to Queue interface operations,LinkedList implements this interface.

Method Syntax:


public E peek()

Return Value:


Method Characteristics

Non-destructive operation

peek() method only "views" the first element of the list without removing it from the list. This is different from poll() or remove() method, which removes the element.

Null-safe

When the list is empty,peek() returns null instead of throwing an exception, which makes it safer than getFirst() or element() in some scenarios.

Time Complexity

Because LinkedList is implemented based on a doubly linked list,peek() method has a time complexity of 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 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 Empty list behavior Throwing an Exception
peek() Returns null No
getFirst() Throws NoSuchElementException Is

4.2 peek() vs element()

Method Empty list behavior Throwing an Exception
peek() Returns null No
element() Throws NoSuchElementException Is

4.3 peek() vs poll()

Method Whether the element is removed Empty list behavior
peek() No Returns null
poll() Is 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() can be used to check the next task to be executed:

Example

LinkedList

<
Task
taskQueue
=
new
LinkedList
<>
(
)

;

// ... Add tasks to the queue

Task nextTask

=

taskQueue.

peek

(

)

;

if

(

nextTask

!=

null

&&

nextTask.

isReadyToExecute

(

)

)

{

   

// Execute tasks

}

Browser history

Simulate a browser viewing the most recently visited page without removing it from the 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: Because peek() may return null, you should perform a null check before using the return value to avoid NullPointerException.

  2. Concurrent Environment:LinkedList is not thread-safe; if used in a multi-threaded environment peek(), additional synchronization measures are needed.

  3. Performance considerations: Although peek() operation itself is O(1), but if called frequently along with other operations, a more efficient data structure may need to be considered.

  4. Comparison with stack operations: In LinkedList When used as a stack,peek() what is viewed is the first element (top of the stack), which is consistent with Stack The class's peek() method behavior.

Java LinkedList Java LinkedList