Suppose we want to sort a hashmap based on the value. We implement a priorityQueue with comparator to do this. As a result, the resulting pq is sorting from the largest to the smallest from index 0 to end.
Here is the code:
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>(
new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
However, somebody said that it is a maxheap, I understand that heap is just parent value greater than child value but I cannot understand why it is a maxheap? It is just implementing the comparator in a priorityQueue? How does this relates to heap?
Internal structure of a priority queue in java is heap.
This comparator will be used to compare with the parent value in priority queue.