0

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);
        }
    }
}
kriegaex
  • 63,017
  • 15
  • 111
  • 202
Young
  • 1
  • 2
  • The `PriorityQueue` class uses a heap as its implementation. A heap does not know the total ordering of its elements, only what the _next_ element is. Iterating the queue cannot give the elements in order (except by coincidence). The only way to get the elements in order is to repeatedly poll the queue. – Slaw Jul 25 '21 at 02:14
  • thx kriegaex! I think I missed the important point!! helped alot – Young Jul 25 '21 at 04:46

1 Answers1

2

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);
    }
kriegaex
  • 63,017
  • 15
  • 111
  • 202
  • I am sorry, I just noticed the comment by @Unmitigated after posting and followed the link. The answer to the linked question is basically the same as mine. I am going to vote closing this question as a duplicate. Here it is about iterating, not about `toString()`, but it is a duplicate with regard to the solution. – kriegaex Jul 25 '21 at 02:10