Case: ArrayList stores student objects and sorts

 

 

public  class CollectionsDemo {
     public  static  void main (String [] args) {
         // Create collection object 
        ArrayList <Student> arrayList = new ArrayList <Student> (); 

        // Create student object 
        Student s1 = new Student ("linqingxia", 30 ); 
        Student s2 = new Student ("zhangmanyu", 35 ); 
        Student s3 = new Student ("wangzuxian", 33 ); 
        Student s4 = new Student ("liuyan", 33 ); 

        // Add students to the collection
        arrayList.add (s1); 
        arrayList.add (s2); 
        arrayList.add (s3); 
        arrayList.add (s4); 

        // Use Collections to sort the ArrayList collection
         // sort (List <T> list, Comparator <? super T> c) Sort the specified list according to the order caused by the specified comparator. 
        Collections.sort (arrayList, new Comparator <Student> () { 
            @Override 
            public  int compare (Student s1, Student s2) { // The actual parameter of the formal parameter s1 is the second object-> s2 so the following is 35-30 = 5 
                int num = s1.getAge () -s2.getAge ();
                 int num2 = num == 0? S1.getName (). CompareTo (s2.getName ()): num;
                 return num2;
            }
        });

        //遍历集合
        for (Student s : arrayList){
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

operation result:

 

Guess you like

Origin www.cnblogs.com/pxy-1999/p/12690655.html