2010-03-13 24 views
3

我有一個HashMap,其中鍵是一個單詞,值是文本中該字符串的出現次數。現在我想把這個HashMap減少到只有15個最常用的單詞(具有最多的出現次數)。你有什麼想法有效地做到這一點?有效的方法來獲取HashMap中使用最多的鍵 - Java

+2

您想縮小列表的時間?定期? – 2010-03-13 17:52:05

+1

您是否嘗試過谷歌這個問題,或者您只是試圖檢查我們? – Artic 2010-03-13 18:22:53

+2

@Artic:SO的全部是「成爲編程相關問題的Google」。所以像「谷歌是你的朋友」這樣的答案在這裏*不受歡迎。如果您無法回答,請不要評論「Google it」。 – SyntaxT3rr0r 2010-03-13 18:47:50

回答

3

使用陣列的代替的ArrayList通過Pindatjuh的建議可以更好,

public class HashTest { 
     public static void main(String[] args) { 
      class hmComp implements Comparator<Map.Entry<String,Integer>> { 
       public int compare(Entry<String, Integer> o1, 
         Entry<String, Integer> o2) { 
        return o2.getValue() - o1.getValue(); 
       } 
      } 
      HashMap<String, Integer> hm = new HashMap<String, Integer>(); 
      Random rand = new Random(); 
      for (int i = 0; i < 26; i++) { 
       hm.put("Word" +i, rand.nextInt(100)); 
      } 
      ArrayList list = new ArrayList(hm.entrySet()); 
      Collections.sort(list, new hmComp()); 
      for (int i = 0 ; i < 15 ; i++) { 
       System.out.println(list.get(i)); 
      } 

     } 
    } 

EDIT反轉排序順序

+0

+1執行!如果我能做得更多,我會做+2。 – Pindatjuh 2010-03-13 18:10:54

-1

您可以使用LinkedHashMap並刪除最近最少使用的項目。

+0

「最近最少使用的項目」,「LinkedHashMap」在重新插入條目時不會更改元素順序。這不起作用。 – Pindatjuh 2010-03-13 17:53:24

+1

如果重複結束時會發生什麼? – 2010-03-13 17:55:36

2

一種方法我想到的解決這個問題,但它可能不是最高效是:

  • 創建的hashMap.entrySet().toArray(new Entry[]{})陣列。
  • 使用Arrays.sort對此進行排序,創建您自己的Comparator,它將僅比較Entry.getValue()(將其轉換爲整數)。按降序排列,即最先/最高,最低/最低。
  • 迭代已排序的數組,並在達到第15個值時中斷。
+0

親愛的downvoter,請解釋。 – Pindatjuh 2010-03-13 18:48:02

+0

+1爲藍圖,一些downvoters是... – stacker 2010-03-13 22:03:07

0
Map<String, Integer> map = new HashMap<String, Integer>(); 

    // --- Put entries into map here --- 

    // Get a list of the entries in the map 
    List<Map.Entry<String, Integer>> list = new Vector<Map.Entry<String, Integer>>(map.entrySet()); 

    // Sort the list using an annonymous inner class implementing Comparator for the compare method 
    java.util.Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){ 
     public int compare(Map.Entry<String, Integer> entry, Map.Entry<String, Integer> entry1) 
     { 
      // Return 0 for a match, -1 for less than and +1 for more then 
      return (entry.getValue().equals(entry1.getValue()) ? 0 : (entry.getValue() > entry1.getValue() ? 1 : -1)); 
     } 
    }); 

    // Clear the map 
    map.clear(); 

    // Copy back the entries now in order 
    for (Map.Entry<String, Integer> entry: list) 
    { 
     map.put(entry.getKey(), entry.getValue()); 
    } 

使用前15個地圖的入口。或者修改最後4行,只將15個條目放入地圖

相關問題