我有一个字频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;
}
这对我来说似乎有点费解。是否有本地收集工具来完成这项工作?
答案 0 :(得分:1)
我认为你的代码甚至不像写的那样工作。两件事:
使用occurrence
初始化Integer.MAX_VALUE
,而不是仅使用一些任意大的值。
每当您发现不常出现的字词时,请更新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;
}