繁体   English   中英

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

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

例如我们有

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

我想像这样打印它们:

fragments: 5
shards: 5
motes: 3

我会通过首先将值放在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);

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

    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