beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

PriorityQueue Interface in Java Collections

By Chaitanya Singh | Filed Under: Java Collections

In the last tutorial, we have seen how a Queue serves the requests based on FIFO(First in First out). Now the question is: What if we want to serve the request based on the priority rather than FIFO? In a practical scenario this type of solution would be preferred as it is more dynamic and efficient in nature. This can be done with the help of PriorityQueue, which serves the request based on the priority that we set using Comparator.

Java PriorityQueue Example

In this example, I am adding few Strings to the PriorityQueue, while creating PriorityQueue I have passed the Comparator(named as MyComparator) to the PriorityQueue constructor.
In the MyComparator java class, I have sorted the Strings based on their length, which means the priority that I have set in PriorityQueue is String length. That way I ensured that the smallest string would be served first rather than the string that I have added first.

PriorityQueueExample.java

import java.util.PriorityQueue;
public class PriorityQueueExample
{
    public static void main(String[] args)
    {
        
        PriorityQueue<String> queue = 
            new PriorityQueue<String>(15, new MyComparator());
        queue.add("Tyrion Lannister");
        queue.add("Daenerys Targaryen");
        queue.add("Arya Stark");
        queue.add("Petyr 'Littlefinger' Baelish");
      
        /*
         * What I am doing here is removing the highest
         * priority element from Queue and displaying it.
         * The priority I have set is based on the string
         * length. The logic for it is written in Comparator
         */
        while (queue.size() != 0)
        {
            System.out.println(queue.poll());
        
        }
    }
}

MyComparator.java

import java.util.Comparator;

public class MyComparator implements Comparator<String>
{
   @Override
   public int compare(String x, String y)
   {
      return x.length() - y.length();
   }
}

Output:

Arya Stark
Tyrion Lannister
Daenerys Targaryen
Petyr 'Littlefinger' Baelish

Methods of PriorityQueue Class

boolean add(E e): Adds the element into the PriorityQueue.

void clear(): This method removes all the elements from the PriorityQueue.

boolean contains(Element e): This method returns true, if the specified element is present in the Queue.

boolean Offer(E e): Same as add() method.

E peek(): Returns the head(the first element) of the Queue.

E poll(): Removes the head of the Queue and returns it.

boolean remove(E e): This method removes the specified element from the Queue and returns true if the deletion is successful. If the specified element is not present in the Queue then it returns false.

int size(): Returns the size of the Queue.

object[] toArray(): Returns array containing all the elements of Queue.

Method reference: Official documentation.

Enjoyed this post? Try these related posts

  1. Java – Convert Vector to List example
  2. Difference between List and Set in Java
  3. Vector in Java
  4. Java – Search elements in LinkedList example
  5. ArrayList in java with example programs – Collections Framework
  6. Java – Check if a particular key exists in HashMap example

Leave a Reply Cancel reply

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

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap