在哈希映射中获得前10个值

问题描述:

我想弄清楚如何从 HashMap 中获得前10个值。我最初尝试使用 TreeMap ,并按值排序,然后取前10个值,但看起来不是该选项,如 TreeMap 按键进行排序。

I am trying to figure out how could I get the top 10 values from the HashMap. I was initially trying to use the TreeMap and have it sort by value and then take the first 10 values however it seems that that is not the option, as TreeMap sorts by key.

我仍然能够知道哪些键具有最高值, K,V 的映射是 String,Integer

I want to still be able to know which keys have the highest values, the K, V of the map are String, Integer.

也许你应该为存储在hashmap中的值对象实现 Comparable 接口。
然后您可以创建一个包含所有值的数组列表:

Maybe you should implement the Comparable Interface to your value objects stored in the hashmap. Then you can create a array list of all values:

List<YourValueType> l = new ArrayList<YourValueType>(hashmap.values());
Collection.sort(l);
l = l.subList(0,10);

问候