显然TreeMap,使用自定义比较器将是更好的选择,特别是因为它有一种专门为此量身定制的方法:headMap(Key k)它将为您提供直到这个 key 的所有条目。
另一方面,如果你坚持HashMap你可以使用 java-8:
yourMap.entrySet()
.stream()
.sorted(Comparator.comparing(e -> e.getValue(), Comparator.reverseOrder()))
.limit(n)
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
Run Code Online (Sandbox Code Playgroud)