PriorityQueue in Java always stores elements in the ascending order if no comparator is specified during its declaration. This is easily provable by the following code
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
// as no custom comparator is provided, it stores the element in ascending order
pq.add(1);
pq.add(3);
pq.add(0);
pq.add(100);
pq.add(50);
while (pq.peek() != null) {
System.out.println(pq.poll());
}
}
This results in output of
0
1
3
50
100
Now, if I use Java8 to print the elements of the priorityQueue before I apply the peek
method, ideally I should get an output similar to the above one where elements are printed in their increasing order.
pq.forEach(System.out::println);
However, the following piece of code prints the elements in some random order i.e neither in the insertion order nor in ascending order. It gives an output as
0
3
1
100
50
My question is that why does priority queue behave differently when we peek the elements and differently when we just print the elements. Is there some underlying concept that I am missing here ? TIA