您好Stackoverflow genii, 我有一个关于按值而不是键来排序TreeMap的问题。这是一个任务,所以我必须这样做,我不一定需要有人为我输入答案,只是提示我做错了什么。这是我的代码:
import java.security.KeyStore.Entry;
import java.util.Scanner;
import java.util.TreeMap;
public class Assignment2 {
public static void main(String[] args) {
int x = 10;
if(args.length > 0) {
x = Integer.parseInt(args[0]);
}
Scanner in = new Scanner(System.in);
TreeMap<String, Integer> t = new TreeMap<>();
while(in.hasNext()) {
String k = in.next();
Integer cur = t.get(k);
t.put(k, cur == null ? 1 : cur +1);
}
in.close();
//Printing: iterate through two nested for loops,
int curmax = 0;
String curstring = null;
for(int i=0; i<x; i++){
for (java.util.Map.Entry<String, Integer> e : t.entrySet()) {
if(e.getValue() > curmax)
//if the value of e is bigger then the last maximum, set the maximum equal to the value.
curmax = e.getValue();
curstring = e.getKey();
}
System.out.printf("%d %s\n", curmax, curstring);
//Switched order of printing since that's what the example result does.
t.remove(curstring);
curmax =0;
}
}
}