Java Queue peek() example

In this guide, you will learn about the Queue peek() method in Java programming and how to use it with an example.

1. Queue peek() Method Overview

Definition:

The peek() method returns the element at the top of the current queue, without removing it. If the queue is empty this method returns null.

Syntax:

E element = queue.peek();

Parameters:

None

Key Points:

- The method returns the head of the queue or null if the queue is empty.

- Unlike the element() method in the Queue interface, the peek() method does not throw an exception when the queue is empty but rather returns null.

- The method is idempotent, meaning it can be called multiple times without changing the state of the queue.

- It's useful in scenarios where you want a sneak peek of the next item in the queue without necessarily processing it.

2. Queue peek() Method Example

import java.util.LinkedList;
import java.util.Queue;

public class QueuePeekExample {
    public static void main(String[] args) {
        Queue<String> books = new LinkedList<>();

        // Add elements to the queue
        books.add("The Great Gatsby");
        books.add("To Kill a Mockingbird");
        books.add("1984");

        // Peek the queue
        String firstBook = books.peek();
        System.out.println("Peeked book: " + firstBook);
        System.out.println("Queue after peeking: " + books);

        // Peek an empty queue
        books.clear(); // Clearing the queue
        String resultWhenEmpty = books.peek();
        System.out.println("Result of peeking an empty queue: " + resultWhenEmpty);
    }
}

Output:

Peeked book: The Great Gatsby
Queue after peeking: [The Great Gatsby, To Kill a Mockingbird, 1984]
Result of peeking an empty queue: null

Explanation:

In the provided example:

1. We instantiated a LinkedList, which is an implementation of the Queue interface.

2. We added some book titles to the queue using the add() method.

3. We then used the peek() method to retrieve (but not remove) the head of the queue, displaying the result and the unchanged state of the queue afterward.

4. To showcase the behavior on an empty queue, we cleared the queue using the clear() method and tried peeking again. As expected, it returned null since the queue was empty.

The peek() method is a handy feature of the Queue interface in Java, offering a way to inspect the front of a queue without modifying its state, making it particularly useful in scenarios where decisions need to be made based on the head element without dequeuing it.

Related Stack and Queue Class methods

Java Queue offer() example
Java Queue poll() example
Java Queue peek() example
Java Stack push() example
Java Stack pop() example
Java Stack peek() example
Java Stack search() example

Comments