java - 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);
}
}
}
解决方案
您的比较器 lambda 是正确的,您可以按原样使用它。您只需要轮询队列以便以正确的顺序获取元素:
while (!pq.isEmpty()) {
Schedule s = pq.poll();
System.out.println("income:" + s.income + " " + "time: " + s.date);
}
推荐阅读
- perl - 如何在 Windows 上运行带有 CGI 的便携式 Perl?
- c - “知识就是力量”c语言拼图
- javascript - jqGrid 不会显示,只有计数显示
- swift - 如何在 MVVM 架构中使用 RxSwift 将参数发送到视图模型?
- c# - 我的倒数计时器卡住了,游戏没有停止
- grails - 如何在邮件正文中包含 href 标签?
- datetime - 在 datepicker odoo 10 中禁用假期日期
- php - 在 laravel 中查询关系
- python - 在 Python 中计算二进制文件的校验和
- elasticsearch - Elasticsearch 索引批量数据 - java API