【问题标题】:Finding the n largest values in a hashmap [duplicate]在哈希图中查找 n 个最大值 [重复]
【发布时间】:2014-07-11 10:24:59
【问题描述】:

我有一个包含<String, integer> 的哈希图,其中包含以下条目:

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

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

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

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

非常感谢您的提前。

【问题讨论】:

  • 欢迎来到 Stackoverflow。这个论坛的目的是帮助您学习如何编程,而不是为您工作(也许除了好玩)您尝试过什么,遇到了什么问题?
  • @TAsk :实际上我不认为这是您标记的问题的副本。这个问题与 Map 的迭代关系不大,实际上更多的是关于如何在一个值集合中找到 N 个最大值。
  • 看看这个:java2s.com/Code/Java/Collections-Data-Structure/…,你要获取entry set,排序,然后将排序好的entry set的前n项添加到新的map中

标签: java hashmap


【解决方案1】:

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

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;
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2013-12-24
    相关资源
    最近更新 更多