在散列映射中查找n个最大值

时间:2014-05-22 11:43:26

标签: java hashmap

我有一个包含<String, integer>的hashmap,其条目如下:

("a",2)
("ab", 3)
("c",5) etc..

我已经看到问题,他们找到单个最大的值并将其存储在另一个hashmap中,但是我如何能够循环它以便找到“n”个最大的数字并将其放入结果哈希映射

例如对于上面的hashmap条目,如果n为2,它将找到2个最大值并放入结果hashmap

    ("ab", 3)
    ("c", 5) 

非常感谢您的进步。

1 个答案:

答案 0 :(得分:3)

这可能不是最有效的方法,但它应该可以解决您的问题:

static HashMap<String, Integer> nLargest(HashMap<String, Integer> map, int n) { //map and n largest values to search for

    Integer value;
    ArrayList<String> keys = new ArrayList<>(n); //to store keys of the n largest values
    ArrayList<Integer> values = new ArrayList<>(n); //to store n largest values (same index as keys)
    int index;
    for (String key : map.keySet()) { //iterate on all the keys (i.e. on all the values)
        value = map.get(key); //get the corresponding value
        index = keys.size() - 1; //initialize to search the right place to insert (in a sorted order) current value within the n largest values
        while (index >= 0 && value > values.get(index)) { //we traverse the array of largest values from smallest to biggest
            index--; //until we found the right place to insert the current value
        }
        index = index + 1; //adapt the index (come back by one)
        values.add(index, value); //insert the current value in the right place
        keys.add(index, key); //and also the corresponding key
        if (values.size() > n) { //if we have already found enough number of largest values
            values.remove(n); //we remove the last largest value (i.e. the smallest within the largest)
            keys.remove(n); //actually we store at most n+1 largest values and therefore we can discard just the last one (smallest)
        }
    }
    HashMap<String, Integer> result = new HashMap<>(values.size());
    for (int i = 0; i < values.size(); i++) { //copy keys and value into an HashMap
        result.put(keys.get(i), values.get(i));
    }
    return result;
}

我希望这会对你有所帮助。