import java.util.ArrayList;import java.util.Comparator;publicclassStudent{// the first keywordprivate String name;// the second keywordprivate String university;// the ageprivateint age;publicStudent(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;}publicintgetAge(){return age;}public String toString(){return name +", "+ university +", "+ age;}publicstaticvoidmain(String[] args){
Student p1 =newStudent("A","BU",20);
Student p2 =newStudent("C","BU",22);
Student p3 =newStudent("C","BC",23);
Student p4 =newStudent("B","CMU",21);
Student p5 =newStudent("C","BU",19);
ArrayList<Student> arrayList =newArrayList<>();
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(newComparator<Student>(){@Overridepublicintcompare(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 swapreturn o1.getName().compareTo(o2.getName());}elseif(!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 swapreturn 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 swapreturn 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
import java.util.ArrayList;import java.util.Comparator;public class Student { // the first keyword private String name; // the second keyword private String university; public ...