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;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章