我有一個HashMap,其中鍵是一個單詞,值是文本中該字符串的出現次數。現在我想把這個HashMap減少到只有15個最常用的單詞(具有最多的出現次數)。你有什麼想法有效地做到這一點?有效的方法來獲取HashMap中使用最多的鍵 - Java
回答
使用陣列的代替的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反轉排序順序
+1執行!如果我能做得更多,我會做+2。 – Pindatjuh 2010-03-13 18:10:54
您可以使用LinkedHashMap並刪除最近最少使用的項目。
「最近最少使用的項目」,「LinkedHashMap」在重新插入條目時不會更改元素順序。這不起作用。 – Pindatjuh 2010-03-13 17:53:24
如果重複結束時會發生什麼? – 2010-03-13 17:55:36
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個條目放入地圖
- 1. 使用toString()的最有效方法JAVA
- 2. 最有效的清除Java HashMap的方法
- 3. 從Java HashMap中提取ith值的有效方法?
- 4. 什麼是獲取HashMap中元素子集的有效方法?
- 5. 獲取列表的最有效方法?
- 6. Java/Android - 最有效的方法來存儲很多變量
- 7. 從Dictionary獲取最大鍵值的有效方法?
- 8. Python:最有效的方法來獲取組合列表?
- 9. 最有效的方法來獲取字節[]隊列(ListBlockingQueue)
- 10. 最有效的方式來通過多個字段在Java中
- 11. 最有效的方法來獲得最後的初始?
- 12. 什麼是最有效的方法來取代Java中的許多文件中的許多字符串標記?
- 13. 最有效的方法來使用懸停在圖像效果
- 14. 最有效的方式來使用navbars?
- 15. PHP:最有效的方法來使多個fsockopen();連接?
- 16. 最有效的方法來實現多列的表?
- 17. 使用ExecutorService的最有效方法
- 18. 使用php獲取多維數組中的父數組鍵的最快方法
- 19. 方法中的Java HashMap
- 20. 什麼是最有效的方法來獲取豬袋串中的元組?
- 21. 堅持HashMap的最有效方法是什麼?
- 22. 方法使此HashMap更有效率
- 23. 最有效的方法來box/unbox多維原始數組
- 24. 在Java中搜索鍵值對的最快和最有效的方法?
- 25. 使用Java在Hashmap中獲取匹配鍵和值
- 26. 最有效的方法來連接表
- 27. 最有效的方法來從PHP
- 28. 最有效的方法來修改xml
- 29. 最有效的方法來繪製silverlight
- 30. 從javascript中獲取關鍵值的有效方法
您想縮小列表的時間?定期? – 2010-03-13 17:52:05
您是否嘗試過谷歌這個問題,或者您只是試圖檢查我們? – Artic 2010-03-13 18:22:53
@Artic:SO的全部是「成爲編程相關問題的Google」。所以像「谷歌是你的朋友」這樣的答案在這裏*不受歡迎。如果您無法回答,請不要評論「Google it」。 – SyntaxT3rr0r 2010-03-13 18:47:50