There are two ways to do this. In any case, you want to create a custom object that contains both String (the value you want) and an integer (priority).
The first solution is to implement this Comparable data object :
class Data implements Comparable<Data> {
private final String message;
private final int priority;
public Data(String message, int priority) {
this.message = message;
this.priority = priority;
}
@Override
int compareTo(Data other) {
return Integer.valueOf(priority).compareTo(other.priority);
}
}
Then when you do
PriorityQueue<Data> queue = new PriorityQueue<Data>();
the queue will order the elements in the order determined by the method compareTo.
The problem with this solution is that if you want the order to be only on an integer, then the method equalsand your method compareTowill not be consistent, or your method equalswill be wrong.
A better solution would be to use the PriorityQueue constructor , which accepts a Comparator . In this case Data, it would not be necessary to implement Comparable; you just need Comparatorone that defines your order:
public final class OrderDataByPriority implements Comparator<Data> {
public static final OrderDataByPriority INSTANCE = new OrderDataByPriority();
private OrderDataByPriority() {}
@Override
public int compare(Data data1, Data data2) {
return Integer.valueOf(data1.priority).compareTo(data2.priority);
}
@Override
public boolean equals(Object other) {
return other == OrderDataByInteger.INSTANCE;
}
private Object readResolve() {
return INSTANCE;
}
}
Note that since this comparator does not accept data, I made it single.
:
PriorityQueue<Data> queue = new PriorityQueue<Data>(
initialCapacity, OrderDataByPrority.INSTANCE);