Comparator对象集合实现多个条件按照优先级比较
感谢该博主:https://blog.csdn.net/l1028386804/article/details/56513205
一、背景介绍
在日常的java开发中,我们在返回一个对象集合时需要按照对象的某个属性或者某些属性进行排序返回给前端进行展示,例如我最近需要返回一个题库集合,需要先根据指定时间排序然后根据创建时间进行排序,在mysql层进行操作比较麻烦而且浪费时间,我们可以通过程序来进行排序。
二、案例代码
// 实体类
public class People {
private Integer id;
private String name;
private Integer topTime;// 置顶时间
private Integer gmtCreate;// 创建时间
public People(Integer id, String name, Integer topTime, Integer gmtCreate) {
super();
this.id = id;
this.name = name;
this.topTime = topTime;
this.gmtCreate = gmtCreate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getTopTime() {
return topTime;
}
public void setTopTime(Integer topTime) {
this.topTime = topTime;
}
public Integer getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Integer gmtCreate) {
this.gmtCreate = gmtCreate;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", topTime=" + topTime + ", gmtCreate=" + gmtCreate + "]";
}
}
// 排序方法
public class PeopleComparator implements Comparator<People>{
@Override
public int compare(People o1, People o2) {
int result = 0;
// 按照置顶时间排序升序(o1,o2位置互换就是降序)
int topTimeSeq = o2.getTopTime() - o1.getTopTime();
if(topTimeSeq != 0){
result = (topTimeSeq > 0) ? 3 : -1;
}else{
// 按照创建时间排序
topTimeSeq = o2.getGmtCreate() - o1.getGmtCreate();
if(topTimeSeq != 0){
result = (topTimeSeq > 0) ? 2 : -2;
}
}
return result;
}
}
// 测试
public class PeopleTest {
public static void main(String[] args) {
List<People> peopleList = new ArrayList<People>(){
{
add(new People(1,"tom1",0,1));
add(new People(2,"tom2",2,4));
add(new People(3,"tom3",1,3));
add(new People(4,"tom4",0,6));
add(new People(5,"tom5",0,2));
add(new People(6,"tom6",0,5));
}
};
Collections.sort(peopleList,new PeopleComparator());
for(People p:peopleList){
System.out.println(p.toString());
}
}
}
测试结果