对文件中出现的单词排序次数

package FileRead;
import javax.persistence.criteria.CriteriaBuilder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;

class name{
    String name=new String();
    int num=0;
}
public class FileRead {
    public static void main(String[] args) {
        try {
            FileInputStream fs=new FileInputStream("E:\\1.txt");
            Scanner sc= new Scanner(fs);
            int num=0;
            HashMap<String,Integer> ts=new HashMap<String, Integer>();

            LinkedList<name> list =new LinkedList<name>();
            while (sc.hasNext()){
                String s=sc.next();
                if(ts.containsKey(s)){
                    Integer i=ts.get(s)+1;
                    ts.put(s,i);
                }
                else {
                    ts.put(s,1);
                }
                num++;
            }
            System.out.println("开始排序.....");

            int i=0;
            int [] nums=new int[num];
            Set<String> keys=ts.keySet();
            for(String key:keys){

                nums[i]=ts.get(key);
                name n1=new name();
                n1.num=nums[i];
                n1.name=key;
                list.add(n1);
            }
           Collections.sort(list, new Comparator<name>() {
               @Override
               public int compare(name o1, name o2) {
                   if(o1.num<o2.num){
                       return 1;
                   }
                   else if(o1.num==o2.num){
                       return 0;
                   }
                   return -1;
               }
           });
            for(name n1:list){
                System.out.println(n1.num+":"+n1.name);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

整体思想就是先把文件中的数据全部读出来后,存入一个map中。然后对已经存在的他的出现次数+1,然后接着put进去map中。 最后创建一个链表,里面存储name对象。然后对list进行排序,根据Collections.sort(list,new Coparator<name>(){

    public int compare(name n1,name n2){

        if(n1.num<n2.num){

            return 1;        

        }else(n1.num==n2.num){

            return 0;    

        }

        return -1;

    }

})

点赞