小技巧,list<map>排序

list<map>排序,不废话直接上代码

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



 class Test3 {
    public static void main(String[] args) {
        List<Map> list = new ArrayList<>();
 
        list.add(getData(0));
        list.add(getData(3));
        list.add(getData(05));
        list.add(getData(6));
        list.add(getData(2));
 
        System.out.println("排序前" + list);
 

        
        list=ListMapSort(list, "desc", "countScore");
 
        System.out.println("排序后" + list);
    }
 
    private static Map<String, String> getData(int num) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("countScore", String.valueOf(num));
        return map;
    }
    
    //list<map>排序
    //入参:数据,排序规则desc倒叙,空或des正叙,排序字段key
    private static List<Map> ListMapSort(List<Map> list,final String orderd,final String key){
        List<Map> listmap=new ArrayList<>();
         Collections.sort(list, new Comparator<Map>() {
             public int compare(Map o1, Map o2) {
                 if(orderd.equals("desc")){
                     return (o2.get(key).toString()).compareTo(o1.get(key).toString()); 
                 }else  if(orderd.equals("des")||"".equals(orderd)){
                     return (o1.get(key).toString()).compareTo(o2.get(key).toString()); 
                 }else{
                     return 0;
                 }
                 
             }
         });
         return list;
    }
}

 

posted @ 2021-04-12 09:48  咔咔kk  阅读(3805)  评论(1编辑  收藏  举报