在hashmap中查找n个最大值
这个问题在这里已经有了答案:
可能这不是最有效的方法,但它应该解决您的问题:
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;
}
我希望这能帮到您。
链接地址: http://www.djcxy.com/p/17983.html