I have a Map<Integer,Integer> freqMap where each value is the frequency of the key Now I want to build a priorityQueue from this map
I was expecting a constructor like PriorityQueue pq = new PriorityQueue(freqMap.keySet(), comparator); But there is no such constructor. Although I can construct it using a comparator and then add the keySet elements using addAll But that will internally add elements one by one. In case I want to build a max heap out of the key set with comparator as the values. I am not sure how can I do this.
My Thoughts:
one way could be that instead of Integer I make a custom class and wrap those integers and make the class implement a Comparable interface. Then when I pass that collection as a parameter to the priorityQueue constructor it should construct the priority Queue in O(n) time.
Whereas if I use the addAll method then probably it will take O(n log n) time. I am not sure though if my reasoning is correct here. It does seem a little complicated to just use a wrapper class that implements comparable for this tiny purpose.
The comparable will compare based on values so the key with the highest value should be on top.