Priority Queue in Java?

Is it possible in Java to create a PriorityQueue of objects where the key that defines the priority is a member of the object?

All the examples that I see in net insert an integer in the PriorityQueue and extract them. I am looking for an implementation that inserts an instance of an object and is retrieved based on one of its member values, which can be an integer.

+4
source share
1 answer

Yes, PriorityQueue has a constructor that allows you to pass a Comparator to determine the order of the elements. For example, if you have the following Bar class:

 public class Bar { private int priority; // getters / setters ... } 

And you want to create a priority queue that orders items based on the priority field (for example, items with high priority remain in front of the queue), you can use the following:

 Queue<Bar> queue = new PriorityQueue<Bar>(new Comparator<Bar>() { public int compare(Bar a1, Bar a2) { return a2.getPriority() - a1.getPriority(); // adapt this to your needs } }); 

If you have more complex logic in the compare method or if you want to reuse the code, I suggest you create a class, say BarComparator , which implements Comparator<Bar> .

In addition, as an alternative to the above, you can make Bar implement the Comparable interface and use the empty constructor, like this:

 public class Bar implements Comparable<Bar> { private int priority; @Override public int compareTo(Bar b) { return b.getPriority() - this.priority; } } 

Hope this helps.

+17
source

All Articles