Comparator对象集合实现多个条件按照优先级比较

                 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());
		}
	}
}

测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值