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

时间:2013-03-15 15:43:05

标签: java sorting hashmap

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

我希望仍然能够知道哪些键值最高,地图的K, VString, Integer

6 个答案:

答案 0 :(得分:3)

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

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

此致

答案 1 :(得分:3)

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<String,Double> map = new HashMap<String,Double>();
        ValueComparator bvc =  new ValueComparator(map);
        TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(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<String> {

    Map<String, Double> base;
    public ValueComparator(Map<String, Double> 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
    }
}

答案 2 :(得分:0)

我担心你必须遍历整个地图。 Heap是查找前K个元素的常用数据结构,如this book中所述。

答案 3 :(得分:0)

如果你想获得地图的10个最高值(假设值是数字或者至少实现了Comparable),那么试试这个:

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

答案 4 :(得分:0)

假设您有一个Map,但此示例适用于任何类型的

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

答案 5 :(得分:0)

我的答案来自sk2212

首先,你需要实现一个降序比较器:

class EntryComparator implements Comparator<Entry<String,Integer>> {

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

}

然后你可以在这个方法中使用它来获取属性&#34; hashmap&#34;:

public List<Entry<String,Integer>> getTopKeysWithOccurences(int top) {
    List<Entry<String,Integer>> results = new ArrayList<>(hashmap.entrySet());
    Collections.sort(results, new EntryComparator());
    return results.subList(0, top);
}
相关问题