比较器Comparator

package set;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class SetSort {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SortModel sortModel1 = new SortModel();
        sortModel1.setAge(1);
        sortModel1.setName("a");
        SortModel sortModel2 = new SortModel();
        sortModel2.setAge(2);
        sortModel2.setName("b");
        
        List<SortModel> sortModels = new ArrayList<>();
        sortModels.add(sortModel2);
        sortModels.add(sortModel1);
        
         List<SortModel> list = new ArrayList<>();
         list.addAll(sortModels);
        
          Collections.sort(sortModels, new Comparator<SortModel>() {
                @Override
                public int compare(SortModel b1, SortModel b2) {
                    return b2.getAge() - b1.getAge();
                }
            });
    }
}


package set;

public class SortModel {

    private int age;
    
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    
}
原文地址:https://www.cnblogs.com/lxh520/p/8760685.html