-5

我正在制作程序,java我不知道Map在这里最好使用哪种程序。也许Tree, Hash, Map, ...?

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例子吗?

4

1 回答 1

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());

于 2013-09-30T13:37:07.047 回答