java实体类多属性排序
1、定义一个实体类Student,因为主要关注排序,所以实体类略显简单。

2、添加几条数据,为后续实验做准备

3、定义两个排序对象,先按chinese由低到高排序,chinese相同,则english由低到高排序。


4、按chinese由低到高排序,chinese相同,则英语由高到低排序。(即调用排序对象的reversed()方法)


5、按chinese由高到低排序,chinese相同,则english由高到低排序。


6、全部代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Student {
//学号
private String sno;
//语文分数
private float chinese;
//英语分数
private float english;
public Student(String sno, float chinese, float english) {
super();
this.sno = sno;
this.chinese = chinese;
this.english = english;
}
public String getSno() {
return sno;
}
public float getChinese() {
return chinese;
}
public void setChinese(float chinese) {
this.chinese = chinese;
}
public float getEnglish() {
return english;
}
public void setEnglish(float english) {
this.english = english;
}
}
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
students.add(new Student("01", 63.0f, 75f));
students.add(new Student("02", 65.0f, 72f));
students.add(new Student("03", 63.0f, 82f));
students.add(new Student("04", 72.0f, 72f));
students.add(new Student("05", 63.0f, 65f));
Comparator<Student> compareChinese =
Comparator.comparing(Student::getChinese);
Comparator<Student> compareEnglish =
Comparator.comparing(Student::getEnglish);
Collections.sort(students,
compareChinese.thenComparing(compareEnglish));
for (Student s : students) {
System.out.println(s.getSno() + "," + s.getChinese() + ","
+ s.getEnglish());
}
System.out.println("---------------------------------------");
Collections.sort(students,
compareChinese.thenComparing(compareEnglish.reversed()));
for (Student s : students) {
System.out.println(s.getSno() + "," + s.getChinese() + ","
+ s.getEnglish());
}
System.out.println("---------------------------------------");
Collections.sort(students,
compareChinese.reversed().
thenComparing(compareEnglish.reversed()));
for (Student s : students) {
System.out.println(s.getSno() + "," + s.getChinese() + ","
+ s.getEnglish());
}
}
}