且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按值排序哈希表,然后按字母顺序排列

更新时间:2023-02-06 13:58:42

You cannot have a sorted HashMap, as is stated in the Javadoc:

... This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

You will have to put it into a different structure that maintains the order you want it to.

Based on what you provided, it looks like you have a few criteria for your order:

  1. sorted by the Map.Entry value, in descending order
  2. sorted by the Map.Entry key, in ascending order

You can make use of the Stream API, along with the useful Comparators from Map.Entry.

final HashMap<String, Integer> map = new HashMap<>();

map.put("it", 2);
map.put("of", 2);
map.put("the", 2);
map.put("times", 2);
map.put("was", 2);
map.put("best", 1);
map.put("worst", 1);

System.out.println("No Guaranteed Order:");
map.entrySet().stream()
        .forEach(System.out::println);


System.out.println();
System.out.println("With Ordering:");
map.entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue()
                        .reversed()
                .thenComparing(Map.Entry.comparingByKey()))
        .forEach(System.out::println);

And the output:

No Guaranteed Order:
the=2
times=2
of=2
was=2
best=1
worst=1
it=2

With Ordering:
it=2
of=2
the=2
times=2
was=2
best=1
worst=1

相关阅读

技术问答最新文章