Reputation: 55
I have used priority queue to store elements in ascending and descending order but when there are duplicate elements it does not store in identical order.
Ascending Order
import java.util.*;
class PriorityQueueDemo {
public static void main(String args[])
{
PriorityQueue<Integer> pQueue
= new PriorityQueue<Integer>();
// Adding items to the pQueue using add()
pQueue.add(2);
pQueue.add(7);
pQueue.add(4);
pQueue.add(1);
pQueue.add(8);
pQueue.add(1);
// Printing the top element of PriorityQueue
System.out.println(pQueue);
}
}
Output:-
[1, 2, 1, 7, 8, 4]
Also if I am doing descending order it gives wrong output on all 3 cases :- lamda expression, comparator.reverseOrder and custom comparator....
Descending Order
import java.util.*;
class PriorityQueueDemo {
public static void main(String args[])
{
PriorityQueue<Integer> pQueue
= new PriorityQueue<Integer>((a, b) -> b - a);
// Adding items to the pQueue using add()
pQueue.add(2);
pQueue.add(7);
pQueue.add(4);
pQueue.add(1);
pQueue.add(8);
pQueue.add(1);
// Printing the top element of PriorityQueue
System.out.println(pQueue);
}
}
Output:-
[8, 7, 4, 1, 2, 1]
I want elements should be sorted. Please help me!! Thanks in Advance
Upvotes: 0
Views: 382
Reputation: 149
The output you are seeing is how the data structure is stored. Priority Queues in Java are implemented using heaps to determine the next element with priority.
You can see a visualisation using this website to help you understand why outputting the queue prints the way it does.
You can just remove elements to retrieve the next priority using poll()
Upvotes: 2