Java_找出最多的10个单词

Java_找出最多的10个单词

题目:找出一个文本中出现最多的10个单词

思路:每个单词作为key,value统计数量,再排序(先按数量降序,再按字母升序)

 

代码:

public static void main(String[] args) {
        // 找出最多的10个单词
        String text = "aaewewqbifjbsadnwiaflewnrklajreqrdsxzvdasanfosahiohreinroqinrjasnvcjdnsfrquiwnrwiuqonrfsafnk";
        Map<Character, Integer> map = new TreeMap<>();
        char[] chars = text.toCharArray();
        int n = chars.length;
        if (n > 0) {
            int i = 0;
            while (n-- != 0) {
                if(map != null && map.get(chars[i]) != null){
                    Integer integer = map.get(chars[i]);
                    map.put(chars[i], ++ integer);
                }else{
                    map.put(chars[i], 1);
                }
                i ++;
            }
        }

        // Comparator多字段排序
        List<Map.Entry<Character,Integer>> list = new ArrayList<>(map.entrySet());
        // Comparator排序 返回值是int,值越大优先级高
        list.sort((o1, o2) -> {
            int cr = 0;
            // 按单词数量降序排序
            int sort = o2.getValue().compareTo(o1.getValue());
            if(sort != 0){
                cr = (sort > 0) ? 2: -1;
            } else {
                // 按单词升序排列
                sort =  o1.getKey().compareTo(o2.getKey());
                if (sort != 0) {
                    cr = (sort > 0) ? 1: -2;
                }
            }
            return cr;
        });

        System.out.println("数量最多的10个单词: ");
        int count = 0;
        for(Map.Entry<Character,Integer> mapping:list){
            if(count == 10){
                break;
            }
            System.out.println(mapping.getKey()+":"+mapping.getValue());
            count ++;
        }
    }

结果:

数量最多的10个单词: 
a:10
n:10
r:9
i:7
s:7
f:6
w:6
e:5
q:5
d:4

 

原文地址:https://www.cnblogs.com/mmdz/p/15608154.html