本文主要是【java】——java自定义排序Comparator的文章,如果有什么需要改进的地方还请大佬指出??
🎬作者简介:大家好,我是听风与他🥇
??博客首页:CSDN主页听风与他
🌄每日一句:狠狠沉淀,顶峰相见
按成绩从大到小排序,如果成绩相同,按照java分数高低排序
package practice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class 多关键字排序 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Student> list = new ArrayList<Student>();
list.add(new Student("张三", 100, 59));
list.add(new Student("李四", 100, 100));
list.add(new Student("王五", 98, 96));
list.add(new Student("赵六", 96, 98));
list.add(new Student("陈七", 59, 100));
Collections.sort(list,new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
//o1在前,o2在后,-1表示不换,1表示换
if(o1.score>o2.score) return o2.score-o1.score;// <0
else if(o1.score<o2.score) return o2.score-o1.score;// >0
else {
if(o1.java<o2.java) return o1.java-o2.java;
}
return 0;
}
});
for(Student i:list) {
System.out.println(i.toString());
}
}
}
class Student{
public Student(String stuname,int java,int mysql) {
this.stuname = stuname;
this.java = java;
this.mysql = mysql;
this.score = java+mysql;
}
String stuname;
int java;
int mysql;
int score;
//打印对象的时候,默认调用toString()
public String toString() {
return this.stuname+" "+this.java+" "+this.mysql+" "+this.score;
}
}
打印结果
李四 100 100 200
赵六 96 98 194
王五 98 96 194
陈七 59 100 159
张三 100 59 159