我试图在 TreeMap 中找到三个最高值。我写了一个代码是这样做的,但我想问你是否可以提出一个更有效的方法。基本上,我将文本中的每个单词连同它在文本中出现的次数一起保存在 TreeMap 中。然后我使用比较器对值进行排序。然后我遍历新创建的 Map 直到达到最后三个值,这是排序后的最高值并将它们打印出来。我将使用大文本,所以这不是一个很好的方法。这是我的代码:
class Text{
public static void main(String args[]) throws FileNotFoundException, IOException{
final File textFile = new File("C://FileIO//cinderella.txt");
final BufferedReader in = new BufferedReader(new FileReader(textFile));
final TreeMap<String, Integer> frequencyMap = new TreeMap<String, Integer>();
String currentLine;
while ((currentLine = in.readLine()) != null) {
currentLine = currentLine.toLowerCase();
final StringTokenizer parser = new StringTokenizer(currentLine, " \t\n\r\f.,;:!?'");
while (parser.hasMoreTokens()) {
final String currentWord = parser.nextToken();
Integer frequency = frequencyMap.get(currentWord);
if (frequency == null) {
frequency = 0;
}
frequencyMap.put(currentWord, frequency + 1);
}
}
System.out.println("This the unsorted Map: "+frequencyMap);
Map sortedMap = sortByComparator(frequencyMap);
int i = 0;
int max=sortedMap.size();
StringBuilder query= new StringBuilder();
for (Iterator it = sortedMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String,Integer> entry = (Map.Entry<String,Integer>) it.next();
i++;
if(i<=max && i>=(max-2)){
String key = entry.getKey();
//System.out.println(key);
query.append(key);
query.append("+");
}
}
System.out.println(query);
}
private static Map sortByComparator(TreeMap unsortMap) {
List list = new LinkedList(unsortMap.entrySet());
//sort list based on comparator
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
//put sorted list into map again
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}