在Java中获取HashMap中使用最频繁的键的有效方法

3

我有一个HashMap,其中键是单词,值是文本中该字符串出现次数。现在我想将此HashMap缩减为仅包含最常用的15个单词(具有最大出现次数)。你有什么高效的方法吗?


2
你想什么时候减少列表?定期吗? - Valentin Rocher
1
你尝试过谷歌这个问题吗?还是只是想来问问我们? - Artsiom Anisimau
2
@Artic:SO的整个目的就是“成为程序相关问题的谷歌”。所以像“Google是你的朋友”这样的答案在这里是*不受欢迎的。如果你不能回答问题,那就不要评论“Google一下”。 - SyntaxT3rr0r
我认为SO的目的不是问那些已经被问了无数次的(理论性)问题。 - Artsiom Anisimau
4个回答

3

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

        }
    }

编辑倒序排列顺序


2

我想到一种解决方法,但可能不是最有效的方法:

  • 创建一个 hashMap.entrySet().toArray(new Entry[]{}) 的数组。
  • 使用 Arrays.sort 进行排序,并创建你自己的比较器(Comparator),它只会根据 Entry.getValue() 进行比较(将其转换为 Integer 类型)。让它按降序排列,即最高/最多的排在前面,最低/最少的排在后面。
  • 遍历排序后的数组,并在达到第 15 个值时停止。

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

使用 map 的前 15 个条目。或者修改后4行代码,将仅放置15个条目到 map 中。


-1
你可以使用 LinkedHashMap 并移除最近最少使用的项目。

"最近最少使用的项目",当重新插入一个条目时,LinkedHashMap 不会更改元素顺序。这样做是行不通的。 - Pindatjuh
1
如果重复出现在末尾会怎样? - President James K. Polk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接