【问题标题】:how to sort a map by key when the values are the same? [duplicate]当值相同时如何按键对地图进行排序? [复制]
【发布时间】:2021-08-30 18:53:17
【问题描述】:

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

目前它是这样工作的:

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), (CC,5), (BB,5)

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

【问题讨论】:

    标签: java sorting hashmap key-value treemap


    【解决方案1】:

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

    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}
    

    【讨论】:

    • 感谢 Jano,它运行良好
    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 2021-11-10
    • 2019-03-10
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多