Sumit Kumar Agarwal Sumit Kumar Agarwal - 6 months ago 16
Java Question

how to set priority in priority queue

I was learning Java and trying to learn priority queue in collections. I tried with below example from one website:

import java.util.*;
class S
{
public static void main(String args[])
{

PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Rahul");
queue.add("Jai");

System.out.println("iterating the queue elements:");
Iterator<String> itr=queue.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}


}
}


here results came is below:

Amit
Jai
Karan
Vijay
Rahul`


I was expecting the result as :

Amit
Vijay
Karan
Rahul
Jai


I am not able to understand how the result changes from my expectation and what type of normal or default priority is used.

In case i want to get the same result as per my expectation, what should i do using prioiryqueue?

Please help me.

Here i want the exact cause of default ordering in priority queue.

Answer

PriorityQueue uses strings' lexicographic order. That's why output is like that.

If you wanna have the output you wanted to be, then you should use LinkedBlockingQueue.

    Queue<String> queue2 = new LinkedBlockingQueue<String>();
    queue2.add("Amit");
    queue2.add("Vijay");
    queue2.add("Karan");
    queue2.add("Rahul");
    queue2.add("Jai");

    System.out.println("iterating the queue elements:");
    Iterator<String> itr2 = queue2.iterator();
    while (itr2.hasNext()) {
        System.out.println(itr2.next());
    }

Output;

iterating the queue elements: Amit Vijay Karan Rahul Jai

Comments