Search code examples
javapriority-queue

Sort items in queue


I have a class Person which has a field - age. Objects from this class are put in a queue:

ArrayDeque<Person> queue = new ArrayDeque<Person>();

I would like to sort items in a queue in a way that a Person with the biggest value of age property becomes the first in a queue. I tried to use priorityQueue but don't know how to copy values from a normal queue to a priority one and at the same time use a comparator to sort. How do I make it work?

Comparator<Person> sorter = Comparator.comparing(Person::getAge);

PriorityQueue<Person> priorityQueue = new PriorityQueue<Person>(queue, sorter);
(this is obviously invalid, is there a workaround so as to copy the queue and have a comparator at the same time?)

Solution

  • Use the PriorityQueue(Comparator<? super E> comparator) constructor, then call addAll(Collection<? extends E> c).

    Since you said "biggest value of age property becomes the first", you need to reverse the Comparator by calling reversed().

    Since getAge() likely returns an int, you should use comparingInt(ToIntFunction<? super T> keyExtractor).

    Comparator<Person> sorter = Comparator.comparingInt(Person::getAge).reversed();
    
    PriorityQueue<Person> priorityQueue = new PriorityQueue<>(sorter);
    priorityQueue.addAll(queue);