Java PriorityQueue Methods

The PriorityQueue class in Java is part of the java.util package. It provides a priority queue data structure, where elements are ordered based on their natural ordering or by a Comparator provided at queue construction time. The priority queue does not allow null elements and ensures that the head of the queue is the least element with respect to the specified ordering.

This guide covers various methods available in the PriorityQueue class. Each method is described in simple terms to help beginners understand how to use them. These methods enable you to perform common operations such as adding, removing, and inspecting elements in the priority queue.

For more detailed information, please refer to the official Java SE Documentation.

Java PriorityQueue Methods

The table below contains various methods of the Java PriorityQueue class, each with a link to a detailed explanation, examples, and real-world uses. Click on the method names to learn more about how to use them effectively in your applications.

Method Description
add() Adds the specified element to this priority queue.
clear() Removes all of the elements from this priority queue.
comparator() Returns the comparator used to order the elements in this queue, or null if this queue is sorted according to its elements' natural ordering.
contains() Returns true if this queue contains the specified element.
forEach() Performs the given action for each element of the queue until all elements have been processed or the action throws an exception.
iterator() Returns an iterator over the elements in this queue.
offer() Inserts the specified element into this priority queue.
peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.
remove() Removes a single instance of the specified element from this queue, if it is present.
removeAll() Removes all of this collection's elements that are also contained in the specified collection.
removeIf() Removes all of the elements of this collection that satisfy the given predicate.
retainAll() Retains only the elements in this collection that are contained in the specified collection.
size() Returns the number of elements in this collection.
spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this collection.
toArray() Returns an array containing all of the elements in this queue.