自定义compare中的代码简化

优先级: 1、级别升序 2、总分降序 3、德育分降序 4、学号升序
class Student{
	int no;    //学号
	int df;    //德育分
	int cf;    //才华分
	int sum;    //总分
	int level;    //级别
	
	public Student(int no,int df,int cf,int H){
		this.no = no;
		this.df = df;
		this.cf = cf;
		this.sum = df + cf;
		if(df>=H && cf>=H){
			this.level = 1;
		} else if(df>=H){
			this.level = 2;
		} else if(df<H && cf<=H && df>=cf){
			this.level = 3;
		} else {
			this.level = 4;
		}
	}
}

我之前直接写的自定义排序规则代码

Collections.sort(list, new Comparator<Student>(){
			@Override
			public int compare(Student o1, Student o2) {
				if(o1.level>o2.level){   //升序
					return 1;
				}else{
					if(o1.level<o2.level){
						return -1;
					}
					if(o1.sum>o2.sum){   //降序
						return -1;
					}else{
						if(o1.sum<o2.sum){
							return 1;
						}
						if(o1.df>o2.df){	//降序
							return -1;
						}else{
							if(o1.df<o2.df){
								return 1;
							}
							if(o1.no>o2.no){	//升序
								return 1;
							}else{
								if(o1.no<o2.no){
									return -1;
								}else{
									return 0;
								}
							}
						}
					}
				}
			}
		});

简化if-else的自定义排序规则代码

Collections.sort(list, new Comparator<Student>(){
			@Override
			public int compare(Student o1, Student o2) {
				int res1 = o1.level-o2.level;
				int res2 = res1==0?o2.sum-o1.sum:res1;
				int res3 = res2==0?(o2.df-o1.df):res2;
				int res4 = res3==0?(o1.no-o2.no):res3;
				return res4;
			}
		});


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值