简体   繁体   English

如何按降序打印HashMap值,但如果两个或多个值相等,则按键升序打印? (爪哇)

[英]How to print HashMap values in descending order, but if two or more values are equal, print them by keys ascending? (JAVA)

For example we have例如我们有

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

I want to print them like this:我想像这样打印它们:

fragments: 5
shards: 5
motes: 3

I would solve this by first putting the values in a TreeMap我会通过首先将值放在TreeMap来解决这个问题

Then I would sort the keys based on equal values and put them in a LinkedHashMap to preserve the order.然后我会根据相等的值对键进行排序,并将它们放在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);

Based on the excellent answer here , consider the following solution:基于此处的出色答案,请考虑以下解决方案:

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM