java – 如何以相反的顺序打印树形图

前端之家收集整理的这篇文章主要介绍了java – 如何以相反的顺序打印树形图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的作业中,我们从文件中读取文本:

To be,or not to be: that is the question:
Whether ’tis nobler in the mind to suffer

然后计算每次发生的时间.我已经能够打印这张地图未分类,然后我能够制作一个TreeMap并以自然的顺序打印(如下所示).我不知道如何打印相反的顺序.我知道使用比较器的方法,但我有点生锈,所以我做了我可以做的.此外,我不知道如何将比较器设置为反向排序树状图.

这是我的方法打印未排序和自然排序:

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

解决方法

如何将地图复制成新的地图呢?
new TreeMap<String,Integer>(Collections.reverSEOrder())

猜你在找的Java相关文章