Java LinkedList pollLast() Method

The LinkedList.pollLast() method in Java is used to retrieve and remove the last 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. pollLast Method Syntax
  3. Examples
    • Retrieving and Removing the Last Element
    • Handling Empty Lists
  4. Conclusion

Introduction

The LinkedList.pollLast() method is a member of the LinkedList class in Java. It allows you to access and remove the last element of the LinkedList. This method is particularly useful for deque-like structures where you want to process and remove the element at the end of the deque.

pollLast Method Syntax

The syntax for the pollLast method is as follows:

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

Examples

Retrieving and Removing the Last Element

The pollLast method can be used to retrieve and remove the last element of a LinkedList.

Example

import java.util.LinkedList;

public class PollLastExample {
    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 and removing the last element using pollLast() method
        String lastElement = list.pollLast();

        // Printing the removed element and the updated LinkedList
        System.out.println("Removed element: " + lastElement);
        System.out.println("Updated LinkedList: " + list);
    }
}

Output:

Removed element: Orange
Updated LinkedList: [Apple, Banana]

Handling Empty Lists

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

Example

import java.util.LinkedList;

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

        // Retrieving and removing the last element from an empty list
        String lastElement = list.pollLast();

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

Output:

The list is empty.

Conclusion

The LinkedList.pollLast() method in Java provides a way to retrieve and remove the last element of a LinkedList. By understanding how to use this method, you can efficiently manage collections of objects in your Java applications, particularly in deque-like structures. 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