【发布时间】:2022-06-10 17:51:20
【问题描述】:
使用 java Comparator 我想获得具有更高值的最低索引。
- 案例 1
| Index | Score |
| ----- | ------|
| 1 | 100 |
| 1 | 110 |
| 2 | 150 |
输出应该是 1 - 110
- 案例 2
| Index | Score |
| ----- | ----- |
| 1 | null |
| 1 | null |
| 2 | 150 |
| 2 | 110 |
输出应该是 2 - 150
下面的代码给出了异常,而且我知道它不会提供预期的输出。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CompareMe {
private int index;
private Integer score;
public CompareMe(int index, Integer score) {
this.index = index;
this.score = score;
}
public int getIndex() {
return index;
}
public Integer getScore() {
return score;
}
public static void main(String[] args) {
List<CompareMe> list = new ArrayList<>();
list.add(new CompareMe(1, 100));
list.add(new CompareMe(1, 110));
list.add(new CompareMe(2, 150));
CompareMe max = Collections.max(list, Comparator.comparingInt(CompareMe::getIndex).reversed()
.thenComparing(CompareMe::getScore));
System.out.println(max.getIndex() + "-" + max.getScore());
list = new ArrayList<>();
list.add(new CompareMe(1, null));
list.add(new CompareMe(1, null));
list.add(new CompareMe(2, 150));
list.add(new CompareMe(2, 110));
max = Collections.max(list, Comparator.comparingInt(CompareMe::getIndex).reversed()
.thenComparing(CompareMe::getScore));
System.out.println(max.getIndex() + "-" + max.getScore());
}
}
【问题讨论】:
-
酷,但是你的代码和minimal, reproducible example在哪里?
-
@Chaosfire 我已经添加了我试图获得预期输出的代码
标签: java