将具有最低地图值的键转置到集合中

时间:2012-04-22 17:41:34

标签: java collections hashmap set

我有一个字频Map<String, Integer>的地图。我需要制作一组发生率最低的单词。说最低出现的单词都出现了两次,我需要制作一组所有这些两次出现的单词。到目前为止,我有:

public Set findRarest()
{
    int occurrence = 1000;  //high initial value for word length
    for (Map.Entry<String,Integer> item : wcMap.entrySet())
    {
        if (item.getValue() > occurrence);        //most likely for performance
        else if (item.getValue() == occurrence)
        {
            rarest.add(item.getKey());
        }
        else                                      //found new lowest count
        {
            rarest.clear();
            rarest.add(item.getKey());
        }
    }
    return rarest;
}

这对我来说似乎有点费解。是否有本地收集工具来完成这项工作?

1 个答案:

答案 0 :(得分:1)

我认为你的代码甚至不像写的那样工作。两件事:

  1. 使用occurrence初始化Integer.MAX_VALUE,而不是仅使用一些任意大的值。

  2. 每当您发现不常出现的字词时,请更新occurrence的值。

  3. 除此之外,您的解决方案很好。我不确定你能不能把自己限制在Java Collections Framework班级。

    更新的代码:

    public Set findRarest()
    {
        Set<String> rarest = new HashSet<String>();
    
        int occurrence = Integer.MAX_VALUE;  //high initial value for word length
        for (Map.Entry<String,Integer> item : wcMap.entrySet())
        {
            if (item.getValue() == occurrence)
            {
                rarest.add(item.getKey());
            }
            else if ( item.getValue() < occurrence )
            {
                occurrence = item.getValue();
                rarest.clear();
                rarest.add(item.getKey());
            }
        }
        return rarest;
    }
    
相关问题