2014-12-07 97 views
0

可以说我有一个大约40k值的散列表。安排排序和打印大型HashMap的最快方法?

我需要得到排名前10位的数值较高的数值为,降序排列。

HashMap<String,Double> balances = new HashMap<String,Double>(); 

我知道我可以只是循环和检查对最后一个值容易获得最高的平衡,但我怎样才能最有效地获得前10名没有多个循环?

希望的输出:

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

你为什么用'的HashMap <字符串,双>'而不是'TreeMap的<双,字符串>'这个应用程序?附注:在附近使用“Double”和“balance”可以设置我的代码气味传感器处理财务金额。 – 2014-12-07 02:58:57

+0

@MichaelT这只是游戏的虚拟金额。 – ThatGuy343 2014-12-07 03:03:31

+1

它仍然是货币。你仍然有四舍五入的错误。我强烈建议您使用固定点数学系统进行任何形式的货币交易 - 无论多么微不足道。 – 2014-12-07 03:04:48

回答

1

甲分钟级堆的数据结构将在这种情况下很方便。您可以一次添加元素,每次大小超过10时删除顶层元素(最小元素)。

下面是数据结构的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",.2); 
    balances.put("test10", 2223.3); 
    balances.put("test11", 101.2); 
    balances.put("test12", 200.1); 

    return balances; 
    } 

} 
+0

我将如何实例化一个?对我的需求来说非常完美 – ThatGuy343 2014-12-07 03:01:40

+1

您可以在Java中使用PriorityQueue实现。 – 2014-12-07 03:05:32