优先级: 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; } });