首页 > 解决方案 > 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);
        }
    }
}

标签: javapriority-queue

解决方案


您的比较器 lambda 是正确的,您可以按原样使用它。您只需要轮询队列以便以正确的顺序获取元素:

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

推荐阅读