【算法-字符串】统计一个字符串中字符出现的次数,按照出现次数升序排序,如果出现次数相同则按照字典顺序,如果有大写则大写出现在小写之后

【算法-字符串】统计一个字符串中字符出现的次数,按照出现次数升序排序,如果出现次数相同则按照字典顺序,如果有大写则大写出现在小写之后

public class Main { 
    public static void main(String[] args) { 
        HashMap<Character, Integer> hashMap = new HashMap();

        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        // 字符串转字符数组
        char[] chars = input.toCharArray();
        // 遍历字符数组,统计字符数组中每个字符出现的次数
        for (char c : chars) { 
            if (hashMap.containsKey(c)) { 
                hashMap.put(c, hashMap.get(c)+1);
            } else { 
                hashMap.put(c, 1);
            }
        }

        ArrayList<Map.Entry<Character, Integer>> list = new ArrayList<>();
        list.addAll(hashMap.entrySet());

        ValueComparator vc = new ValueComparator();

        Collections.sort(list, vc);

        for (int i = 0; i < list.size(); i++) { 
            System.out.print(list.get(i).getKey() + ":" + list.get(i).getValue() + ";");
        }
    }

    /** * 按照字符出现的次数升序排序,如果出现次数相同则按照字典顺序,如果有大写则大写出现在小写之后 */
    private static class ValueComparator implements Comparator<Map.Entry<Character, Integer>> { 
        @Override
        public int compare(Map.Entry<Character, Integer> m, Map.Entry<Character, Integer> n) { 
            //首先是按照 value 值来进行比较
            int v = n.getValue() - m.getValue();
            if (v == 0) { 
                // 如果value值相同则按照key的值进行比较
                // 如果都是大写字母或小写字母按照字典顺序
                if ((!Character.isUpperCase(m.getKey()) && !Character.isUpperCase(n.getKey())) ||
                        (Character.isUpperCase(m.getKey()) && Character.isUpperCase(n.getKey()))) { 
                    return m.getKey() - n.getKey();
                } else { 
                    //如果有大写和小写,则小写在前,大写在后
                    return n.getKey() - m.getKey();
                }
            } else { 
                return v;
            }
        }
    }
}
    原文作者:runewbie
    原文地址: https://blog.csdn.net/runewbie/article/details/107144281
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞