package itcast;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.TreeSet;
public class Forth {
/**
* 键盘录入一个字符串,计算出每个字符出现的次数
* 按照次数大小进行排序
*/
public static void main(String[] args) {
demo1();
//demo2();
}
/**
*
*/
private static void demo2() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串");
String s = sc.nextLine();
HashMap<Character, Integer> hm = new HashMap<>();
char[] array = s.toCharArray();
for (Character c : array) {
if (!hm.containsKey(c)) {
hm.put(c, 1);
}else {
hm.put(c, hm.get(c) + 1);
}
}
Collection<Integer> values = hm.values();
TreeSet<Integer> ts = new TreeSet<>(new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
int num = i2 - i1;
return num == 0 ? 1 : num;
}
});
ts.addAll(values);
for (Integer integer : ts) {
for (Character c : hm.keySet()) {
if (hm.get(c) == integer) {
System.out.print(c + "(" + hm.get(c) + ")");
}
}
}
}
|
|