如何以相反顺序打印树形图 [英] How to Print treemap in reverse order

查看:70
本文介绍了如何以相反顺序打印树形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的作业中,我们从文件中读取以下文本:

In my assignment we are read from a file the text:

成为或不成为:这是一个问题:
是否让头脑中的高贵遭受痛苦

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

然后计算每次发生的次数.我已经能够未分类地打印该地图,然后能够制作一个TreeMap并以自然顺序打印(如下所示).我不知道如何反向打印.我知道一种使用比较器的方法,但是我有些生疏,所以我已经尽力了.此外,我不知道如何设置比较器以将树形图按相反的顺序排序.

then count the times each has occured. I've been able to print this map unsorted, then I was able to make a TreeMap and print it in natural order (which is shown below). I don't know how to print in reverse order. I know a way to use a comparator, but I'm a little rusty so I've done what I can. Furthermore, I don't know how to set the comparator up to sort the Treemap into reverse order.

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

Here's my method to print Unsorted and Naturally sorted:

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

推荐答案

将地图复制到自然逆序的新地图中怎么办?

What about copying your Map into a new one naturally reverse ordered?

new TreeMap<String,Integer>(Collections.reverseOrder())

这篇关于如何以相反顺序打印树形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆