2

単語頻度のマップがありますMap<String, Integer>。最も出現頻度の低い単語のセットを作成する必要があります。最少出現単語がすべて 2 回出現するとします。これらの 2 回出現するすべての単語のセットを作成する必要があります。これまでのところ、私は持っています:

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

これは私には少し複雑に思えます。これを行うためのネイティブの収集ツールはありますか?

4

1 に答える 1

1

あなたのコードが書かれたとおりに機能するとは思いません。2つのこと:

  1. 任意の大きな値の代わりに初期化occurrenceInteger.MAX_VALUEます。

  2. occurrence出現頻度の低い単語を見つけるたびに、 の値を更新します。

それ以外は、あなたのソリューションは問題ありません。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;
}
于 2012-04-22T18:44:21.740 に答える