1、要排序的实体例子
package com.xiangxue.jack.test;
//实现Comparable<Students>
public class Students implements Comparable<Students>{
private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Students(String name, int score) {
this.name = name;
this.score = score;
}
//实现这个方法
//降序
//如果需要升序this.score-o.score
@Override
public int compareTo(Students o) {
return o.score-this.score;
}
}
2、test代码
@Test
public void testList(){
List<Students> list = new ArrayList<>();
list.add(new Students("ss",90));
list.add(new Students("ss",70));
list.add(new Students("ss",100));
list.add(new Students("ss",30));
list.add(new Students("ss",60));
list.add(new Students("ss",50));
list.add(new Students("ss",40));
list.add(new Students("ss",99));
list.add(new Students("ss",88));
list.add(new Students("ss",77));
list.add(new Students("ss",66));
list.add(new Students("ss",33));
Collections.sort(list);
list.stream().limit(10).forEach(ll -> {
System.out.println(ll.getScore());
});
}
3、结果
100
99
90
88
77
70
66
60
50
40