PriorityQueue
expects elements to be comparable to each other. It doesn't explicitly track the priority of each element itself. It just compares them to each other. That means you'll need to the elements and their priorities into the queue in pairs.
One way to do that is to add Map.Entry
s directly and create the queue with a custom comparator.
PriorityQueue<Map.Entry<Integer, Integer>> queue =
new PriorityQueue<>(Comparator.comparing(entry -> entry.getValue()));
queue.addAll(map.entrySet());
Another way would be to create a simple class holding both values that implements Comparable
. Something like:
class ElementPriority implements Comparable<ElementPriority> {
int element;
int priority;
@Override public int compareTo(ElementPriority other) {
return Integer.compare(this.priority, other.priority);
}
}
Or if you want to get really hacky you could combine each pair of int
s into a long
holding both values. If you store the priorities in the big end then the elements should naturally sort by priority.
PriorityQueue<Long> queue = new PriorityQueue<>();
map.forEach((element, priority) -> {
queue.add((priority & 0xFFFFFFFFL) << 32 | (element & 0xFFFFFFFFL));
});
This is highly dubious, but hey, what the heck.