5

I'd like to know how can I add a value to a PriorityQueue with a specific value.

I have a Map<Integer, Integer> // element -> value and I'd like to insert elements to the PriorityQueue with the value priority.

For example:

Map{1=0, 3=5265, 5=22375, 7=4202, 9=233, 11=351, 13=119}

should have this order in the Queue:

{1, 13, 9, 11, 7, 3, 5}
4
  • You can insert the Map.Entrys in the PriorityQueue and provide a Comparator of these. Or create your own Pair type with the priority and value with an associated Comparator. Commented Mar 31, 2015 at 23:11
  • possible duplicate of Java: How do I use a PriorityQueue? Commented Mar 31, 2015 at 23:11
  • @SotiriosDelimanolis I have no idea how that should be done. Commented Mar 31, 2015 at 23:14
  • You should probably read @Stefan's link. Commented Mar 31, 2015 at 23:15

1 Answer 1

5

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.Entrys 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 ints 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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm still a bit confused. The 1st method give me a cast error. I think i'll try the 2nd one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.