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

我试图找出如何从HashMap获得前10个值。 我最初尝试使用TreeMap并按值排序,然后取前10个值,但似乎这不是选项,因为TreeMap按键排序。

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

也许您应该将Comparable Interface实现为存储在hashmap中的值对象。 然后,您可以创建所有值的数组列表:

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

问候

 import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Testing { public static void main(String[] args) { HashMap map = new HashMap(); ValueComparator bvc = new ValueComparator(map); TreeMap sorted_map = new TreeMap(bvc); map.put("A",99.5); map.put("B",67.4); map.put("C",67.4); map.put("D",67.3); System.out.println("unsorted map: "+map); sorted_map.putAll(map); System.out.println("results: "+sorted_map); } } class ValueComparator implements Comparator { Map base; public ValueComparator(Map base) { this.base = base; } // Note: this comparator imposes orderings that are inconsistent with equals. public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } // returning 0 would merge keys } } 

恐怕你必须遍历整个地图。 堆是一种常用的数据结构,用于查找前K个元素,如本书所述 。

如果您尝试获取地图的10个最高值(假设值是数字或至少实现Comparable),请尝试以下操作:

 List list = new ArrayList(hashMap.values()); Collections.sort(list); for(int i=0; i<10; i++) { // Deal with your value } 

假设你有一个Map,但是这个例子适用于任何类型的

 Map m = yourMethodToGetYourMap(); List c = new ArrayList(m.values()); Collections.sort(c); for(int i=0 ; i< 10; ++i) { System.out.println(i + " rank is " + c.get(i)); } 

我的答案来自于sk2212

首先,您需要实现降序比较器:

 class EntryComparator implements Comparator> { /** * Implements descending order. */ @Override public int compare(Entry o1, Entry o2) { if (o1.getValue() < o2.getValue()) { return 1; } else if (o1.getValue() > o2.getValue()) { return -1; } return 0; } } 

然后你可以在像这个属性“hashmap”这样的方法中使用它:

 public List> getTopKeysWithOccurences(int top) { List> results = new ArrayList<>(hashmap.entrySet()); Collections.sort(results, new EntryComparator()); return results.subList(0, top); }