2012-04-22 21 views
2

我有地图的单词频率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

不是真的。番石榴的'Multiset'可能会使它不那么笨拙,但这基本上就是做这件事的方法 - 除了没有任何理由拥有'if(item.getValue()>出现)'行外。 – 2012-04-22 17:57:10

回答

1

我不认为你的代码,甚至可以作为写。两件事情:

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

谢谢。我确实错过了事件的更新。 Integer.MAX_VALUE也是一个好主意。我已经使用了第一个“如果”来提高性能,因为一旦遇到一个简短的单词,大多数时候你只会做一次评估。你的解决方案大部分时间都会做两次评估。我可能会错过一些东西。 – Bol 2012-04-22 19:12:33

+0

作为@LouisWasserman在他的评论中指出,在大多数情况下,你是在浪费你的时间在该水平进行优化。在* javac编译*和[JIT编译器(http://en.wikipedia.org/wiki/Just-in-time_compilation)是在使这些种类的优化确实不错。我猜测,如果你真的做了一些时间测试,你会发现它没有什么区别。 – ulmangt 2012-04-22 19:20:55

+0

这真的很好知道。谢谢。 – Bol 2012-04-22 19:27:15