嘿,每个人都有对象存储多个整数值。我希望它按降序排序多次,一次按“Wins”值降序,另一次按“播放”值降序等等......我怎么能这样做?
答案 0 :(得分:0)
以下是问题的示例代码
public class MyObject {
private int wins;
private int played;
// to do add getter and setter method for the above fields
}
List<MyObject> objects = new ArrayList<MyObject>();
// to do java code for creating Myobjects
在Java 8之前:
// wins sorting
objects.sort(new Comparator<MyObject>() {
@Override
public int compare(MyObject m1, MyObject m2) {
return m2.getWins() - m1.getWins();
}
});
// Played sorting
objects.sort(new Comparator<MyObject>() {
@Override
public int compare(MyObject m1, MyObject m2) {
return m2.getPlayed() - m1.getPlayed();
}
});
Java 8代码:
objects.sort(Comparator.comparingInt(MyObject::wins) .reversed());
objects.sort(Comparator.comparingInt(MyObject::played) .reversed());