为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Java

         

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;

    }

})

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
数据库工程师
手记
粉丝
52
获赞与收藏
361

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消