【BigData】Java基礎_讀取文件並統計文件中每個單詞出現的次數


需求

從test.txt文件中讀取內容,並且統計每個單詞在文件中出現的次數,文件內容如下:

hello ZhangSan
hello Lisi
hello Xiaohua

實現代碼

實現邏輯:

①先使用BufferedReader讀取文件中的內容

②將讀取到的內容存儲到數組中,並且根據分隔符將單詞分隔

③在HashMap中進行統計個數

package cn.test.logan.day09;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 從文件test.txt中讀取內容,統計每個單詞出現的次數
 * @author QIN
 *
 */
public class WordCount {
    public static void main(String[] args) throws Exception {
        
        //創建一個HashMap對象
        HashMap<String,Integer> map = new HashMap<>();
        // 新建BufferedReader對象
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/test.txt")));
        //定義一個數組,將讀取到的元素先放到數組中
        String line = "";
        while((line = br.readLine())!=null){
            String[] wordline = line.split(" ");
            for(String word:wordline){
                if(map.containsKey(word)){ // 判斷是否存在該單詞
                    Integer value = map.get(word); //存在則將value+1,不存在則直接新增即可
                    map.put(word, value+1);
                }else{
                    map.put(word, 1);
                }    
            }
        }
        // 關閉流
        br.close();
        /**
         * 循環遍歷map
         */
        // 取出set集合
        Set<String> keyset = map.keySet();
        // 根據key取出value
        for(String key:keyset){
            int value = map.get(key);
            System.out.println(key+":"+value);
        }
        System.out.println("----------------------------");
        // 使用Entry打印
        Set<Entry<String, Integer>> entrySet = map.entrySet();
        for(Entry<String, Integer> ent:entrySet){
            System.out.println(ent.getKey() + ":" + ent.getValue());
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM