查询文件中出现次数最多的单词(使用单一职责模式)

1、加载文件,获取文件中的内容(一次读一行,存入到StringBuilder中)
2、获取文件中所有的单词(使用正则表达式),得到String[]数组
3、将单词和出现的次数存入到map中
4、统计map中最大的value值
5、遍历map中的key,将值与value相同的key存入到list中。
6、这样就找到了出现次数最多的单词。

代码如下

public class Test5 {

    public static String loadFile(String path){
        StringBuilder str = new StringBuilder();
        try {
            Reader reader = new FileReader(path);
            BufferedReader br = new BufferedReader(reader);
            String line = null;
            while((line=br.readLine())!=null){
                str.append(line);
            }
            br.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return str.toString();
    }
    public static String[] parseWords(String string){
        String[] str = string.split("[^a-zA-Z]+");
        return str;
    }
    public static Map countWords(String[] strings){
        Map<String,Integer> map = new HashMap<>();
        for (String str:strings) {
            if(map.containsKey(str)){
                Integer n = map.get(str);
                map.put(str,++n);
            }else{
                map.put(str,1);
            }
        }
        return map;
    }
    public static Integer maxValue(Map<String,Integer> map){
        Collection<Integer> c = map.values();
        Integer n = Collections.max(c);
        return n;
    }
    public static List getKeyByMaxValue(Map<String,Integer> map,Integer maxValue){
        List<String> list = new ArrayList<>();
        for (Map.Entry<String,Integer> entry:map.entrySet()) {
            if(entry.getValue()==maxValue){
                list.add(entry.getKey());
            }

        }
        return list;
    }

    public static void main(String[] args) {
        String str = loadFile("F://a.txt");
        String[] strings = parseWords(str);
        Map<String,Integer> map = countWords(strings);
        Integer maxValue = maxValue(map);
        List<String> list = getKeyByMaxValue(map,maxValue);
        System.out.println(list.toString());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值