如何对Java中的值反转命令Map <key,value =“”>?</key,>

时间:2013-09-30 13:32:43

标签: java

我正在java制作节目,我不知道这里最适合使用哪种Map。可能是TreeHashMap...

degree.put("a",5);
degree.put("b",2);
degree.put("c",4);
degree.put("d",2);
degree.put("e",3);
degree.put("f",5);

现在我必须根据给定的整数值

对此列表进行排序

排序地图应为:

{a=5, f=5, c=4, e=4, b=4, d=2}

有人可以提供code示例吗?

1 个答案:

答案 0 :(得分:4)

试试这个

private static HashMap sortByComparator(HashMap unsortMap) {
            HashMap sortedMap = new LinkedHashMap();         
            try {       
                List list = new LinkedList(unsortMap.entrySet());

                // sort list based on comparator
                Collections.sort(list, new Comparator() {
                    public int compare(Object o1, Object o2) {
                        return ((Comparable) ((Map.Entry) (o1)).getValue())
                                .compareTo(((Map.Entry) (o2)).getValue());
                    }
                });

                // put sorted list into map again
                //LinkedHashMap make sure order in which keys were inserted

                for (Iterator it = list.iterator(); it.hasNext();) {
                    Map.Entry entry = (Map.Entry) it.next();
                    sortedMap.put(entry.getKey(), entry.getValue());
                }
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            return sortedMap;
        }

如果您想按降序排列,请将return语句更改为return ((Comparable) ((Map.Entry) (o2)).getValue()) .compareTo(((Map.Entry) (o1)).getValue());