Reputation: 3089
Can't think about a better way printing toString with PQ, natural ordered, than copying the entire collection to another one, and using poll method.
Any other suggestions?
Upvotes: 0
Views: 450
Reputation: 533462
If you need the order the PriorityQUeue would be if it were fully sorted, you need to copy it to a Sorted collection like TreeSet
e.g.
System.out.println(new TreeSet(pq)); // prints elements naturally sorted.
Note: this will discard duplicates, a PriorityQueue does not.
Even though sorting is O(n * log n) and printing is O(n) This is not the whole story. Sorting in memory is much faster than using any IO meaning that you need an insanely large queue for the sorting to be more significant.
public static void main(String... args) {
PriorityQueue<Double> pq = new PriorityQueue<Double>();
for (int i = 0; i < 10*1000 * 1000; i++)
pq.add(Math.random());
long start1 = System.nanoTime();
Set<Double> set = new TreeSet<Double>(pq);
long time1 = System.nanoTime() - start1;
long start2 = System.nanoTime();
for (Double d : set) {
System.out.println(d);
}
long time2 = System.nanoTime() - start2;
System.out.printf("It took %.3f seconds to sort, and %.3f seconds to print %,d doubles%n", time1 / 1e9, time2 / 1e9, pq.size());
}
prints at the end
It took 28.359 seconds to sort, and 94.844 seconds to print 10,000,000 doubles
If I use an array and sort that it is
Double[] doubles = pq.toArray(new Double[pq.size()]);
Arrays.sort(doubles);
It took 8.377 seconds to sort ....
In short, you are likely to run out of memory or exceed the maximum length of a String before you have a queue long enough for sorting to be the most significant.
Upvotes: 1
Reputation: 19185
You need to Override toString()
method in the Object which you are adding in Any collection thentoString
Method works fine
PriorityQueue<String> priorityQueue = new PriorityQueue<String>();
priorityQueue.add("one");
priorityQueue.add("two");
priorityQueue.add("three");
System.out.println(priorityQueue);//Prints [one, two, three]
Upvotes: 0