假设我有一个大约有40k值的散列图。
我需要按降序排列排名前10的键值。
HashMap<String,Double> balances = new HashMap<String,Double>();
我知道通过循环和检查最后一个值可以轻松获得最高平衡,但是如何在没有多个循环的情况下有效地获得前十名呢?
期望的输出:
1. <key> has balance of 500
2. <key> has balance of 400
3. <key> has balance of 300
4. <key> has balance of 200
5. <key> has balance of 100
6. <key> has balance of 50
7. <key> has balance of 45
8. <key> has balance of 40
9. <key> has balance of 30
10. <key> has balance of 10
答案 0 :(得分:1)
在这种情况下,最小优先级堆数据结构会很方便。你可以一次性添加元素,每次大小超过10时删除顶部元素(min元素)。
以下是数据结构HashMap的基本实现:
import java.util.*;
public class Test
{
public static void main(String[] args)
{
PriorityQueue<Map.Entry<String,Double>> queue = new PriorityQueue<>(10, new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Map.Entry<String,Double> x, Map.Entry<String,Double> y)
{
if (x.getValue() < y.getValue())
{
return -1;
}
if (x.getValue() > y.getValue())
{
return 1;
}
return 0;
}
});
HashMap<String,Double> balances = new HashMap<String,Double>();
balances = Test.populateBalances(); // return the populated map
for (Map.Entry<String, Double> entry : balances.entrySet()) {
queue.add(entry);
if (queue.size() > 10)
queue.poll();
}
for (Map.Entry<String, Double> entry : queue)
System.out.println(entry.getKey() + ":" + entry.getValue());
}
public static HashMap<String, Double> populateBalances() {
HashMap<String,Double> balances = new HashMap<String,Double>();
balances.put("test1", 1000.2);
balances.put("test2", 200.3);
balances.put("test3", 12000.2);
balances.put("test4", 2050.3);
balances.put("test5", 1034.2);
balances.put("test6", 210.3);
balances.put("test7", 10.2);
balances.put("test8", 0.3);
balances.put("test9", 13210.2);
balances.put("test10", 2223.3);
balances.put("test11", 101.2);
balances.put("test12", 200.1);
return balances;
}
}