如何以相反的顺序打印树状图简短的回答:长答案:
在我的作业中,我们从文件中读取文本:
成为,或不成为:这就是一个问题:
在心中是否更崇高地受苦
然后计算每个发生的时间。我已经能够打印此地图未排序,然后我能够制作一个树状图并以自然顺序打印它(如下所示)。我不知道如何以相反的顺序打印。我知道使用比较器的方法,但我有点生锈,所以我已经尽了我所能。此外,我不知道如何设置比较器以将树状图排序为相反的顺序。
以下是我打印“未排序”和“自然排序”的方法:
private static void sortPrintFrequencies(Map<String,Integer> vocabulary, PrintStream output {
Iterator iterator = vocabulary.keySet().iterator();
System.out.println("Unsorted");
while (iterator.hasNext()) {
String key = iterator.next().toString();
String value = vocabulary.get(key).toString();
String times = "times.";
String appears = "appears";
System.out.printf("%35s", key + " " + appears + " " + value + " "+ times);
System.out.println();
}
System.out.println("========================================");
System.out.println("SORTED NATURALLY BY KEY");
TreeMap newVocabulary = new TreeMap(vocabulary);
Iterator iterator2 = newVocabulary.keySet().iterator();
while (iterator2.hasNext()) {
String key = iterator2.next().toString();
String value = newVocabulary.get(key).toString();
String times = "times.";
String appears = "appears";
System.out.printf("%35s", key + " " + appears + " " + value + " "+ times);
System.out.println();
}
TreeMap revVocabulary = new TreeMap(new RevCmpKey());
System.out.println("========================================");
}
这是我的比较器:
import java.util.*;
public class RevCmpKey implements Comparator<String> {
public int compare(String e1, String e2) {
//compareTo in String classs
if(e1.compareTo(e2) <1)return -1;
if(e1.compareTo(e2) >1)return 1;
return 0;
}
}