当值相同时如何按键对地图进行排序?

how to sort a map by key when the values are the same?

我目前正在按值对地图进行排序,但我想不出在具有相同值的情况下如何按键对其进行排序。

目前是这样工作的:

public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        @Override
        public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
            return e2.getValue().compareTo(e1.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

我的输出是这样的: (AA,10), (抄送,5), (BB,5)

我正在努力实现这一目标: (AA,10), (BB,5), (CC,5)

如果值相同,您可以检查您的比较器,如果是,则比较键。这是您修改后的方法:

public static <K extends Comparable<? super K>, V extends Comparable<? super V>> Map<K, V> newSortMapByValue(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
                // Check if values are the same
                if (e1.getValue().equals(e2.getValue()))
                    // Compare e1 to e2, because A should be first element
                    return e1.getKey().compareTo(e2.getKey());
                else
                    // Compare e2 to e1, because largest number should be first
                    return e2.getValue().compareTo(e1.getValue());
            }
        });

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

主要示例:

    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("AA",10);
        map.put("CC",5);
        map.put("BB",5);
        map.put("DD",15);
        map.put("ZZ",15);

        System.out.println(map);
        Map sortedMap = newSortMapByValue(map);
        System.out.println(sortedMap);
    }

输出:

{AA=10, CC=5, BB=5, DD=15, ZZ=15}
{DD=15, ZZ=15, AA=10, BB=5, CC=5}