Answer the question
In order to leave comments, you need to log in
PriorityQueue sorted by priority, how to fix?
I have a simple class:
public class User {
private String name;
private int ID;
public User (String name, int ID) {
this.name = name;
this.ID = ID;
}
public int GetID () {
return ID;
}
public String toString () {
return name + " : " + ID;
}
}
public class Main <T> {
public static void main (String [] args) {
Queue <User> queue = new PriorityQueue <User> (10, new Comparator <User> () {
@Override
public int compare(User o1, User o2) {
// TODO Auto-generated method stub
return (o1.GetID() - o2.GetID());
}
});
queue.add(new User ("Example", 10));
queue.add(new User("Example", 3));
queue.add(new User("Example", 1));
queue.add(new User("Example", 5));
queue.add(new User ("Example", 7));
queue.stream().forEach(System.out::println);
}
}
Example : 1
Example : 5
Example : 3
Example : 10
Example : 7
Answer the question
In order to leave comments, you need to log in
PriorityQueue is a heap , so it doesn't guarantee order when traversed, only order when element is retrieved:
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
queue.stream().forEach(System.out::println);
never do this with any data structures at all. PPS Read the Java Style Guide . Because the stream() method, just like iterator(), does not guarantee traverses in order of priority. There is a poll method for this.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question