map的排序总结

1、按键排序


使用treemap按照键来排序

@Test 
    public void treeMap(){
        
        //传入的比较器只能根据key来排序,TreeMap如不指定排序器,默认将按照key值进行升序排序
        //指定排序器按照key值降序排列 ,
        //Comparator中泛型必须传入key类型的的超类TreeMap(Comparator<? super K> comparator) 

        TreeMap<String, Integer> treeMap=new TreeMap<String, Integer>(new Comparator<Object>() {

            @Override
            public int compare(Object o1, Object o2) {
                return o2.hashCode()-(o1.hashCode());
                
                //如果key是String类型   return o2.compareTo(o1);
            }
        }) ;
        treeMap.put("2", 1);  
        treeMap.put("b", 1); 
        treeMap.put("1", 1);  
        treeMap.put("a", 1);  
        System.out.println("treeMap="+treeMap);  
    
    }



 2、按值排序

/**
     * @see map排序
     * @param oriMap
     * @return
     */
    public static Map<String, Integer> sortMapByValue(Map<String, Integer> oriMap) {
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        if (oriMap != null && !oriMap.isEmpty()) {
            List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(oriMap.entrySet());
            Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
                @Override
                public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                    return o2.getValue() - o1.getValue();
                }
            });
            Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
            Map.Entry<String, Integer> tmpEntry = null;
            while (iter.hasNext()) {
                tmpEntry = iter.next();
                sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
            }
        }
        return sortedMap;
    }


你可能感兴趣的:(排序,map)