一、Comparable封装排序规则方式
1、要排序的对象实现Comparable接口,并重写抽象排序规则方法compareTo(Vip o);
/**
* 描述:可被List快捷排序的bean
*
* @author zsg
* @date 2022-01-22
*/
public class Vip implements Comparable<Vip> {
/**
* 等级
*/
private int grade;
/**
* 积分
*/
private int score;
public Vip(int grade, int score) {
this.grade = grade;
this.score = score;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Vip o) {
//这里可定义排序规则
if (getGrade() - o.grade == 0){
//等级相同,比较积分
return getScore() - o.getScore();
}
//等级不同比较等级
return getGrade() - o.getGrade();
}
}
2、调用Collections排序:
List<Vip> vips = new ArrayList<>();
Collections.sort(vips);
二、Comparator临时排序规则方式
使用此排序规则bean类可以不实现Comparable接口
List<Vip> vips = new ArrayList<>();
Collections.sort(vips, new Comparator<Vip>() {
@Override
public int compare(Vip o1, Vip o2) {
if (o1.getGrade() - o2.getGrade() == 0){
//等级相同,比较积分
return o1.getScore() - o2.getScore();
}
//等级不同比较等级
return o1.getGrade() - o2.getGrade();
}
});