题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.*;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String reg = "[0-9a-z]+";
String a = in.nextLine();
if (!Pattern.matches(reg, a)) {
System.out.println("输入不合规");
return;
}
// 首先将数据封装到treeMap中,并默认以ASCII码进行升序排序
Map<Character, Integer> map = new TreeMap<>();
for (char c : a.toCharArray()) {
if(map.get(c)==null) {
map.put(c, 1);
} else {
map.put(c, map.get(c)+1);
}
}
// 然后再把map封装到List中,以map的value值进行排序
List<Map.Entry<Character, Integer>> entryList = new ArrayList<>(map.entrySet());
entryList.sort(new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
// forEach匿名内部类遍历
entryList.forEach(new Consumer<Map.Entry<Character, Integer>>() {
@Override
public void accept(Map.Entry<Character, Integer> characterIntegerEntry) {
System.out.print(characterIntegerEntry.getKey());
}
});
}
}
