Java—统计字符出现次数

题意:
test.txt文件中每行是由n个字母组成的一个字符串;读取文件,然后输出该文件中出现次数最多的前10个字母,以及每个字母出现的次数

/**
 * @Author: whm
 * @Description: 统计字符个数
 * @Date:Created 2019/11/28
 */
public class StatCharNum {

    public static void main(String[] args) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        stat(new File("D:\\test.txt"));
        System.out.println("\n运行时间:" + stopwatch.stop().elapsed(TimeUnit.MILLISECONDS) + "毫秒");
    }

    /**
     *统计文件中出现次数最多的前10个字符串
     * @param file 文件
     */
    public static void stat(File file){
        //定义字符读取(缓冲)流
        BufferedReader bfr = null;

        try{
            bfr = new BufferedReader(new FileReader(file));
            //定义一个临时接收文件中的字符串变量
            String tmpValue = null;
            //接收文件中所有字符串的变量
            String newValue = "";

            //开始读取文件中的字符
            while (StringUtils.isNotEmpty(tmpValue=bfr.readLine())){
                newValue=newValue+tmpValue;
            }

            char[] ch = newValue.toCharArray();

            //定义一个Map,键对应字符,值对应字符出现的次数
            Map<Character,Integer> lm = new LinkedHashMap<>();

            //遍历ch,将ch中所有的字符存入lm中
            for(int i = 0;i < ch.length; i++){
                char c = ch[i];
                if(lm.containsKey(c)){//如果map中有该键,则取出该键中的值并进行+1操作
                    int count = lm.get(c);
                    lm.put(c, count + 1);
                } else{//如果没有出现该键就说明是第一次出现,直接存入1次
                    lm.put(c, 1);
                }
            }

            //map排序:按照value的大小进行降序排
            ValueComparator vc=new ValueComparator(lm);
            Map<Character,Integer> sortedMap=new TreeMap<>(vc);
            sortedMap.putAll(lm);

            //取出TreeMap中已经排好序的前10个键值对
           if( sortedMap.size()<10){
               System.out.println(sortedMap);
           }else {
               Map<Character,Integer> result=new LinkedHashMap<>();
               List<Map.Entry<Character,Integer>> list=new ArrayList<>(sortedMap.entrySet());
               for(Map.Entry<Character,Integer> s:list.subList(0,10)){
                   result.put(s.getKey(),s.getValue());
               }
               System.out.println(result);
           }

        }
        catch(IOException e){
            System.out.println("文件读取错误");
        }
        finally{
            try{
                if(bfr!=null)
                    bfr.close();
            }
            catch(IOException e){
                System.out.println("文件关闭错误");
            }
        }
    }
}

/**
 * @Author: whm
 * @Description: 自定义TreeMap的排序规则:按照map中value的大小进行降序排
 * @Date:Created 2019/11/28
 */
public class ValueComparator implements Comparator<Character> {
    Map<Character, Integer> base;
    public ValueComparator(Map<Character, Integer> base) {
        this.base = base;
    }

    public int compare(Character a, Character b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        }
    }
}

你可能感兴趣的:(*【Java】,日常的算法练习)