ArrayList 多关键字自定义排序

mac2024-03-14  19

import java.util.ArrayList; import java.util.Comparator; public class Student { // the first keyword private String name; // the second keyword private String university; // the age private int age; public Student(String name, String university, int age) { this.name = name; this.university = university; this.age = age; } public String getName(){ return name; } public String getUniversity() { return university; } public int getAge() { return age; } public String toString() { return name + ", " + university + ", " + age; } public static void main(String[] args) { Student p1 = new Student("A", "BU", 20); Student p2 = new Student("C", "BU", 22); Student p3 = new Student("C", "BC", 23); Student p4 = new Student("B", "CMU",21); Student p5 = new Student("C", "BU", 19); ArrayList<Student> arrayList = new ArrayList<>(); arrayList.add(p1); arrayList.add(p2); arrayList.add(p3); arrayList.add(p4); arrayList.add(p5); System.out.println("Before sort:"); for(Student p: arrayList){ System.out.println(p); } // create an instance of anonymous inner class "Comparator" arrayList.sort(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { // Attention: The position of o1 is in back of that of o2. if(!o1.getName().equals(o2.getName())) { // directly compare the first keywords of two objects // < 0: wrong order, swap; > 0: right order, don't swap return o1.getName().compareTo(o2.getName()); }else if(!o1.getUniversity().equals(o2.getUniversity())){ // the first keywords of two objects are equal, so we continue to compare the second keywords of two objects // < 0: wrong order, swap; > 0: wrong order, don't swap return o1.getUniversity().compareTo(o2.getUniversity()); }else{ // In Java 1.8, the compare method must return 0 in some cases. // < 0: wrong order, swap; = 0: equal, don't swap; > 0: right order, don't swap return o1.getAge() - o2.getAge(); } } }); System.out.println(""); System.out.println("After sort:"); for(Student p: arrayList){ System.out.println(p); } } } Before sort: A, BU, 20 C, BU, 22 C, BC, 23 B, CMU, 21 C, BU, 19 After sort: A, BU, 20 B, CMU, 21 C, BC, 23 C, BU, 19 C, BU, 22
最新回复(0)