程序如下:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一串字符串:");
String line = sc.nextLine();
char[] arr = line.toCharArray();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (char c :arr ) {
if (map.containsKey(c)) {
map.put(c, map.get(c)+1);
}else{
map.put(c, 1);
}
}
TreeMap<Integer, Character> tm = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer i1,Integer i2){
int num = i2 - i1;
return num == 0 ? 1 : num;
}
});
for (Character c : map.keySet()) {
tm.put(map.get(c), c);
}
System.out.println(tm);
for (Integer key : tm.keySet()) {
System.out.println(tm.get(key) + "=" + key);
}
}
运行结果如下:
请输入一串字符串:
aaabbbbcccccccddddddeeeeeeeeee
{10=e, 7=c, 6=d, 4=b, 3=a}
null=10
null=7
null=6
null=4
null=3
请问为什么遍历时候打印的都是null?
|
|