簡體   English   中英

在HashMap中獲取最常用鍵的有效方法 - Java

[英]Efficient way to get the most used keys in a HashMap - Java

我有一個HashMap,其中鍵是一個單詞,值是文本中該字符串出現的次數。 現在我想將這個HashMap減少到只有15個最常用的單詞(出現次數最多)。 你有任何想法有效地做到這一點嗎?

Pindatjuh建議使用數組而不是ArrayList可能會更好,

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) );
            }

        }
    }

編輯反向排序順序

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

  • 創建一個hashMap.entrySet().toArray(new Entry[]{})數組。
  • 使用Arrays.sort對此進行Arrays.sort ,創建自己的Comparator ,它將僅在Entry.getValue() (將其轉換為Integer)上進行比較。 使其順序降序,即最高/最高,最低/最低。
  • 迭代排序的數組並在達到第15個值時中斷。
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個條目放入地圖中

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM