我有简单的类(class)
public class ActiveAlarm {
public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;
}
和List<ActiveAlarm>
骗局。如何按timeStarted
升序排序,然后按timeEnded
?有人可以帮忙吗?我知道 C++ 中有通用算法和重载运算符 <,但我对 Java 很陌生。
最佳答案
例如:
class Score {
private String name;
private List<Integer> scores;
// +accessor methods
}
<小时/>
Collections.sort(scores, new Comparator<Score>() {
public int compare(Score o1, Score o2) {
// compare two instance of `Score` and return `int` as result.
return o2.getScores().get(0).compareTo(o1.getScores().get(0));
}
});
从 Java 8 开始,您可以简单地使用 lambda 表达式来表示 Comparator 实例。
Collections.sort(scores, (s1, s2) -> { /* compute and return int */ });
关于java - 如何按某些属性对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909054/