【问题标题】:How to print HashMap values in descending order, but if two or more values are equal, print them by keys ascending? (JAVA)如何按降序打印 HashMap 值,但如果两个或多个值相等,则按键升序打印? (JAVA)
【发布时间】:2020-04-09 05:55:50
【问题描述】:

例如我们有

Map<String, Integer> map = new HashMap<>();
map.put("fragments", 5);
map.put("motes", 3);
map.put("shards", 5);

我想像这样打印它们:

fragments: 5
shards: 5
motes: 3

【问题讨论】:

标签: java sorting dictionary hashmap


【解决方案1】:

我会通过首先将值放入 TreeMap 来解决这个问题

然后我会根据相等的值对键进行排序并将它们放在一个 LinkedHashMap 保留订单。

      Map<String, Integer> map = new TreeMap<>();
      map.put("motes", 3);
      map.put("shards", 5);
      map.put("fragments", 5); 

      map = map.entrySet().stream().sorted(Comparator.comparing(
            Entry<String, Integer>::getValue).reversed()).collect(
                  LinkedHashMap<String, Integer>::new,
                  (map1, e) -> map1.put(e.getKey(), e.getValue()),
                  LinkedHashMap::putAll);

      map.entrySet().forEach(System.out::println);

【讨论】:

    【解决方案2】:

    基于出色的答案here,考虑以下解决方案:

        public static void main(String[] args) {
            final Map<String, Integer> originalMap = new HashMap<>();
            originalMap.put("fragments", 5);
            originalMap.put("motes", 3);
            originalMap.put("shards", 5);
    
            final Map<String, Integer> sortedMap = sortByValue(originalMap, false);
    
            sortedMap
                    .entrySet()
                    .stream()
                    .forEach((entry) -> System.out.println(entry.getKey() + " : " + entry.getValue()));
    
        }
    
        private static Map<String, Integer> sortByValue(Map<String, Integer> unsortedMap, final boolean ascending) {
            List<Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());
    
            // Sorting the list based on values
            list.sort((o1, o2) -> ascending ? o1.getValue().compareTo(o2.getValue()) == 0
                    ? o1.getKey().compareTo(o2.getKey())
                    : o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0
                    ? o2.getKey().compareTo(o1.getKey())
                    : o2.getValue().compareTo(o1.getValue()));
            return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new));
    
        }
    

    【讨论】:

      猜你喜欢
      • 2023-01-21
      • 2021-09-13
      • 1970-01-01
      • 2022-08-18
      • 2021-11-10
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多