Java LinkedList peek() Method

The LinkedList.peek() method in Java is used to retrieve, but not remove, the first element of a LinkedList. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality.

Table of Contents

  1. Introduction
  2. peek Method Syntax
  3. Examples
    • Retrieving the First Element
    • Handling Empty Lists
  4. Conclusion

Introduction

The LinkedList.peek() method is a member of the LinkedList class in Java. It allows you to access the first element of the LinkedList without removing it. This method is particularly useful for queue-like structures where you want to inspect the element at the front of the queue without modifying the queue.

peek Method Syntax

The syntax for the peek method is as follows:

public E peek()
  • Returns: The first element of this list, or null if this list is empty.

Examples

Retrieving the First Element

The peek method can be used to retrieve the first element of a LinkedList.

Example

import java.util.LinkedList;

public class PeekExample {
    public static void main(String[] args) {
        // Creating a LinkedList of Strings
        LinkedList<String> list = new LinkedList<>();

        // Adding elements to the LinkedList
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Retrieving the first element using peek() method
        String firstElement = list.peek();

        // Printing the first element
        System.out.println("First element: " + firstElement);
    }
}

Output:

First element: Apple

Handling Empty Lists

If the LinkedList is empty, the peek method returns null.

Example

import java.util.LinkedList;

public class PeekEmptyListExample {
    public static void main(String[] args) {
        // Creating an empty LinkedList of Strings
        LinkedList<String> list = new LinkedList<>();

        // Retrieving the first element from an empty list
        String firstElement = list.peek();

        // Checking if the list is empty
        if (firstElement == null) {
            System.out.println("The list is empty.");
        } else {
            System.out.println("First element: " + firstElement);
        }
    }
}

Output:

The list is empty.

Conclusion

The LinkedList.peek() method in Java provides a way to retrieve, but not remove, the first element of a LinkedList. By understanding how to use this method, you can efficiently inspect the front element of a queue-like structure without modifying the list. Handling the potential return value of null ensures your code remains robust and can handle empty lists gracefully.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top