[英]Transposing keys with lowest values of a map to a 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;
}
在我看來這有點令人費解。 是否有本機收集工具可以完成此任務?
我認為您的代碼甚至都無法像編寫的那樣工作。 兩件事情:
使用Integer.MAX_VALUE
而不是只是一些任意的大值初始化occurrence
。
更新的值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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.