T
T
thatmaniscool2018-07-02 19:50:45
Java
thatmaniscool, 2018-07-02 19:50:45

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;
  }
}

I create the main class, where I set the priority parameters for the queue.
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);
  }
}

At the exit
Example : 1
Example : 5
Example : 3
Example : 10
Example : 7

I can not find the reason why it is not sorted.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-07-02
@thatmaniscool

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());
}

PS You shouldqueue.stream().forEach(System.out::println); never do this with any data structures at all. PPS Read the Java Style Guide .

D
Denis Zagaevsky, 2018-07-02
@zagayevskiy

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 question

Ask a Question

731 491 924 answers to any question