2015-05-11 125 views
1

我試圖解決排序包含大量數據(1000K)的地圖。 有沒有比這更有效的方法來排序這些地圖?下面是 是代碼片段。Map <String,Integer>和Map <Integer,String>排序

Map<Integer, String> myMap1 = new HashMap<Integer, String>(); 
    Map<String,Integer> myMap2 = new HashMap< String,Integer>(); 

    List <Entry<Integer,String>> lst1 = new ArrayList<Entry<Integer,String>>(myMap1.entrySet()); 
    Collections.sort(lst1, new Comparator<Entry<Integer,String>>(){ 
     @Override 
     public int compare(Entry e1, Entry e2) 
     { 
      return ((String) e1.getValue()).compareTo((String) e2.getValue()); 
     }} 
    ); 


    List <Entry<String,Integer>> lst2 = new ArrayList<Entry<String,Integer>>(myMap2.entrySet());   
    Collections.sort(lst2, new Comparator<Entry<String,Integer>>(){ 
     @Override 
     public int compare(Entry e1, Entry e2) 
     { 
      return ((Integer) e1.getValue()).compareTo((Integer) e2.getValue()); 
     }} 
    ); 
+0

您是否從數據庫獲取數據? – dsharew

+4

聽起來像一個XY問題。爲什麼你需要在內存中排序如此多的數據? – Reimeus

+1

「1000K」是什麼意思? 100萬*條目*? –

回答

1

IMO優先級隊列也可以是一個好辦法:

Map<Integer, String> myMap1 = new HashMap<Integer, String>(); 
PriorityQueue<Entry<Integer, String>> pq = new PriorityQueue<Map.Entry<Integer,String>>(myMap1.size(), new Comparator<Entry<Integer, String>>() { 
    @Override 
    public int compare(Entry<Integer, String> arg0, Entry<Integer, String> arg1) { 
     return arg0.getValue().compareTo(arg1.getValue()); 
    } 
}); 
pq.addAll(myMap1.entrySet()); 
while (!pq.isEmpty()) { 
    System.out.println(pq.poll()); 
} 

也是谷歌番石榴可以是一個很好的選擇,因爲它提供了一個BIMAP實現可反轉,然後只是排序上反轉地圖鍵。

Map<Integer, String> myMap1 = new HashMap<Integer, String>(); 
    // insert values in myMap 
    Map<String,Integer> myMap2 = myMap1.inverse(); 
    SortedMap<Integer, Character> sortedInversed = new TreeMap<Integer, Character>(myMap2); 
+3

使用「TreeMap」而不是「HashMap」會更好。 'TreeMap'已經排序。 –

+0

在TreeMap插入將是O(lg n),因爲它將是O(1)在Map中。另外IMO'Set'和'Map'不能很好地處理重複。 –

+1

*國際海事組織和地圖不能很好地處理重複*看起來你沒有以正確的方式使用它們,但這不在問題之列。另外,插入'PriorityQueue'需要花費時間O(lg n),因此無論您選擇何種數據結構,您都必須支付該價格才能進行排序。 –

相關問題