从键盘接收一行字符串, 统计每个字符出现的次数
按照字符出现的个数排序, 次数相同的按照字典顺序排序: a=1, d=1, c=2, b=3- import java.util.Comparator;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Scanner;
- import java.util.Set;
- import java.util.TreeMap;
- import java.util.TreeSet;
- public class abc {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- String str = sc.nextLine();
- sc.close();
- sortByCount(str);
- }
- private static void sortByCount(String str) {
- char[] arr = str.toCharArray();// 字符串装换为字符数组
- Map<Character, Integer> map = new TreeMap<>();
- putInMap(arr, map);//将键 和值装入集合
-
- // 获取键值对,封装到Entry中,然后将Entry对象添加到TreeSet集合中,TreeSet中传一个比较器.
- Set<Entry<Character, Integer>> entrySet = map.entrySet();
- TreeSet<Entry<Character, Integer>> ts = new TreeSet<>(
- new Comparator<Entry<Character, Integer>>() {
- @Override
- public int compare(Entry<Character, Integer> e1,
- Entry<Character, Integer> e2) {
- int num = e2.getValue() - e1.getValue();
- return num == 0 ? e1.getKey().compareTo(e2.getKey())
- : num;
- }
- });
- ts.addAll(entrySet);
- System.out.println(ts);
- }
- private static void putInMap(char[] arr, Map<Character, Integer> map) {
- for (Character ch : arr) {
- map.put(ch, map.get(ch) == null ? 1 : map.get(ch) + 1);
- }
- }
- }
复制代码 |