用java代码写单词统计

先利用io流
FileInputStream字节流读取数据,转换成字符流InputStreamReader,
用BufferedReader字符缓冲流 因为有readline()每次读取一行的方法

 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/wcinput/wc.txt")));
 //map 存储键值对
        Map<String, Integer> map = new HashMap<>();
      String line = "";
        while ((line = br.readLine()) != null) {  
        String[] arr = line.split(" ");
            for (String word : arr) {
            if (map.get(word) == null) {
                    map.put(word, 1);
                      } else {
                    map.put(word, map.get(word) + 1);
                }
                
    //map集合中keySet() 把所有的key放到set集合中  遍历map集合中所有的key
        Set<String> set = map.keySet();
          for (String str : set) {
            System.out.println(str + " " + map.get(str));
        }

猜你喜欢

转载自blog.csdn.net/L__MY/article/details/88906602