java 內部類實現排序 Comparator


public class A{

    public xxxx fun(){
        //業務邏輯
        //xxxxxxxxxxxxxxxxxxx
        //排序
        Collections.sort(myList, new MyComparator(configValueList));
    }
    /**
    *內部類實現排序
    *configValueList 排序規則
    *根據DtoList中的某一個字段,按照configValueList配置的規則來排序
    *如configValueList ["a","b","c"]
    *myList    myList.get[0].getVal() = b,myList.get[1].getVal() = a,myList.get[2].getVal() = c
    *那么排序后 myList.get[0].getVal() = a,myList.get[1].getVal() = b,myList.get[2].getVal() = c
    */
    class MyComparator implements Comparator<Dto> {
        private List<String> configValueList;

        public MyComparator(List<String> configValueList) {
            this.configValueList = configValueList;
        }

        @Override
        public int compare(Dto dto1, Dto dto2) {
            if(CollectionUtils.isEmpty(configValueList) || dto1 == null || dto2 == null){
                return 0;
            }
            String val1 = dto1.getVal();
            String val2 = dto2.getVal();
            if(StringUtils.isBlank(val1) || StringUtils.isBlank(val2)){
                return 0;
            }
            int sort1 = configValueList.indexOf(val1);
            int sort2 = configValueList.indexOf(val2);
            if(-1 == sort1 || -1 == sort2){
                return 0;
            }
            return sort1 - sort2;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM