Search code examples
javapriority-queue

How to Sort PriorityQueue in Java with class


I know there are lots of answers about this problem. I tried following it but it wont show the result that I want. there is an
input
60 3
50 2
20 1
40 2
30 3
30 1

and I'm expecting the
output
60 3
50 2
40 2
30 3
30 1
20 1

but if i print the priorityQueue it will show

60 3
50 2
40 2
20 1
30 3
30 1

I dont' knwo why..

This is my code below

import java.util.*;

public class MaximumIncomeSchedule {
    static class Schedule  {
        int income;
        int date;

        public Schedule(int i, int d) {
            income = i;
            date = d;
        }
       
    }
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        PriorityQueue<Schedule> pq = new PriorityQueue<>(n,(o1, o2) -> {
            if(o2.income==o1.income)
                return o2.date - o1.date;
            return o2.income - o1.income;
        });
        int mD = 0;
        for (int i = 0; i < n; i++) {
            int M = sc.nextInt();
            int D = sc.nextInt();
            Schedule s = new Schedule(M, D);
            pq.add(s);
            mD = Math.max(mD, D);
        }
        for (Schedule s : pq) {
            System.out.println("income:" + s.income + " " + "time: " + s.date);
        }
    }
}

Solution

  • Your comparator lambda is correct, you can use it as-is. You just need to poll the queue in order to fetch the elements in the correct order:

        while (!pq.isEmpty()) {
          Schedule s = pq.poll();
          System.out.println("income:" + s.income + " " + "time: " + s.date);
        }