一个文件,其中内容以换行与空格作为每个单词的分隔,手写代码,将单词按单词的出现次数排序



import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.junit.Test;

public class solution {
    @Test
    public void testFunc() throws Exception{
        sortWord();
    
    }
    public void sortWord() throws Exception{
        //把文件分割成字符串存入hashMap
        BufferedReader bis = new BufferedReader(new FileReader("D:/javaShiYan.txt"));
        String lineString = null;
        HashMap<String, Integer> hashMap = new HashMap<String,Integer>();
        while ((lineString=bis.readLine()) != null) {
            
            String[] strArray = lineString.split(" ");
            insertIntoMap(strArray, hashMap);
        }
        
        //将hashMap集合的关系存入list, 利用collections对list进行排序,并编写比较器
        ArrayList<Map.Entry<String,Integer>> list =
                new ArrayList<Map.Entry<String,Integer>>(hashMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {

            @Override
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue().intValue());
            }
            
        });
        for(Map.Entry<String,Integer> entry:list){
            System.out.println(entry.getKey()+"   "+entry.getValue());
        }
    }
    
    //将string数组存入map集合中
    public void insertIntoMap(String[] strArray, HashMap<String, Integer> map){
        if (strArray.length==0) {
            return;
        }
        for(String str:strArray){
            if (map.containsKey(str)) {
                map.put(str, map.get(str)+1);
            }
            else{
                map.put(str, 1);
            }
        }
    }
    
}

猜你喜欢

转载自blog.csdn.net/wwzheng16/article/details/81003015
今日推荐