AppDividend
Latest Code Tutorials

# PriorityQueue in Java Example | Java PriorityQueue

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a `Comparator` provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit the insertion of non-comparable objects (doing so may result in ClassCastException).

We’ve learned about the Queue before. Now if we want the elements inside the queue to be processed based on their priority, then we use the concept of PriorityQueue.

We’ve seen that queue generally works on the FIFO (First in First out) principle, but when the queue needed to be processed according to some priority, then it is based on a priority heap.

Now the main point of PriorityQueue is the elements of PriorityQueue are ordered in natural ordering or by a Comparator which is provided at queue construction time using a constructor.

## PriorityQueue in Java

A priority queue in Java is a particular type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation.

Some useful points for PriorityQueue to be remembered.

1. It never permits NULL values
2. It is an unbounded queue
3. The front of PriorityQueue contains the least elements according to the specific ordering, and the rare of the priority queue contains the most significant elements.

4. It inherits methods from AbstractQueue, AbstractCollection, Collection, and Object class.

## Constructors in Priority Queue

Now we will learn about some constructors of PriorityQueue.

1. PriorityQueue(): This constructor, a PriorityQueue with an initial capacity of 11 and its ordering, is done by natural order.
2. PriorityQueue(int initial capacity): It creates a PriorityQueue with the specified initial capacity, and the ordering will be a natural ordering
3. PriorityQueue(PriorityQueue pq): It creates a PriorityQueue containing the elements of another specific PriorityQueue.
4. PriorityQueue(SortedSet ss): It creates PriorityQueue with the help of the elements of the specified sorted set.
5. PriorityQueue(Collection c): It creates PriorityQueue with the help of elements of a specific Collection.
6. PriorityQueue(int initial capacity, Comparator comp): It creates PriorityQueue with a specific initial capacity and the order of its elements according to a specified Comparator.

## Methods in PriorityQueue

Now let’s talk about various methods of PriorityQueue class.

With the help of add() method, we insert elements into the priority queue. See the following file Add.java.

```//importing PriorityQueue from util package
import java.util.PriorityQueue;
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//adding element to the queue with the help of offer() method
pq.offer("CSS");

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);
}
}```

See the following output.

### public peek()

This method is used to retrieve (not remove) the head element of priority queue; it also returns NULL if there is no element present in the priority queue. See the following example.

```// Peek.java

//importing PriorityQueue from util package
import java.util.PriorityQueue;
class Peek
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);

// showing the head of the priority queue using peek() method
System.out.println("Head element of the queue is :"+pq.peek());
}
}```

See the following output.

### public remove()

The remove() method removes a single specified element from a priority queue. See the following code.

```// Remove.java

//importing PriorityQueue from util package
import java.util.PriorityQueue;
class Remove
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);

// removing all elements of the queue using clear() method
pq.remove();
System.out.println("After using remove() method elements in the queue :"+pq);
}
}```

See the following output.

### public poll()

It is used to remove and retrieve the head element of a priority queue. See the following code.

```// Poll.java

//importing PriorityQueue from util package
import java.util.PriorityQueue;
class Poll
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);

// removing the head of the priority queue using poll() method

pq.poll();
System.out.println("Head element of the queue is :"+pq);
}
}```

See the following output.

### int size()

The int size() method returns a number of elements in the priority queue.

```// Size.java

//importing PriorityQueue from util package
import java.util.PriorityQueue;
class Size
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);

//calculating size
System.out.println("Size of the PriorityQueue is "+pq.size());
}
}```

See the following output.

### toArray()

The toArray() function is used to return the array containing all the elements of the priority queue.

See the following code.

```//importing PriorityQueue from util package
import java.util.PriorityQueue;
class ToArray
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);

//declaring an array
String[] arr =new String[10];

//returning the elements to the array using toArray() method
String [] arr1=pq.toArray(arr);

System.out.println("Elements in the array:");
for(int i=0;i<pq.size();i++)
{
System.out.println(arr[i]);
}

}
}```

See the following example.

### void clear()

The clear() method is used to remove all the items from the priority queue.

```// Clear.java

//importing PriorityQueue from util package
import java.util.PriorityQueue;
class Clear
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);

// removing all elements of the queue using clear() method
pq.clear();
System.out.println("After using clear() method elements in the queue :"+pq);
}
}```

See the following output.

### boolean offer(element)

This method is used to insert a specified element into the priority queue.

```//importing PriorityQueue from util package
import java.util.PriorityQueue;
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//adding element to the queue with the help of offer() method
pq.offer("CSS");

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);
}
}```

See the following output.

### boolean contains (Object element)

The boolean contains() method returns true if the priority queue contains a specific item.

See the following program.

```// Contains.java

//importing PriorityQueue from util package
import java.util.PriorityQueue;
class Contains
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);

// checking specific element presents or not in the queue using contains method
System.out.println("Is 'C++' present? "+pq.contains("C++"));
System.out.println("Is 'Python' present? "+pq.contains("Python"));
}
}```

See the following output.

### Iterator iterator()

The iterator() method returns the iterator over the elements in this queue. See the following code.

```// IteratorDemo.java

//importing PriorityQueue from util package
import java.util.PriorityQueue;
import java.util.Iterator;
class IteratorDemo
{
public static void main(String []er)
{

//creating a priority queue
PriorityQueue<String> pq= new PriorityQueue<>();

//showing elements of queue
System.out.println("Elements of PriorityQueue are: "+pq);

//creating an iterator
Iterator iq=pq.iterator();

//dispalying values with the help of iterator
System.out.println("The iterator values are:");
while(iq.hasNext())
{
System.out.println(iq.next());
}
}
}```

See the following output.

### Comparator comparator()

The method is used to return comparator, which can be used for ordering the elements of the priority queue. See the following code.

```// Comparator.java

import java.util.Comparator;
import java.util.PriorityQueue;

class DemoComp implements Comparator<String>
{
public int compare(String str1, String str2)
{
String str11;
String str12;
str11 = str1;
str12 = str2;
return str12.compareTo(str11);
}
}

class ComparatorDemo
{
public static void main(String[] er)
{
PriorityQueue<String> q = new PriorityQueue<String>(new DemoComp());

System.out.println("Queue before using the comparator() method: " + q);

System.out.println("Queue after using comparator() method");
for (String i : q)
System.out.print(i + " ");
}
}```

See the following output.

Finally, PriorityQueue in Java Tutorial | Java PriorityQueue Example is today’s topic.

This site uses Akismet to reduce spam. Learn how your comment data is processed.