Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

java - How to Print treemap in reverse order

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

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("========================================");

}

Here's my comparator:

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;
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...