将指定文本(可以通过右侧文件目录下的src/step3/readme.txt查看)以降序的方式输出每个单词出现的次数。

为了完成本关任务,你需要掌握:

1.如何统计相同单词的次数;

2.如何进行排序。

练习要求:
将指定文本(可以通过右侧文件目录下的src/step3/readme.txt查看)以降序的方式输出每个单词出现的次数。

package com.company;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.*;
public class Main {
     public Map<String,Integer> task(String str) {
        Map<String,Integer> map=new HashMap<String, Integer>();
        StringTokenizer t=new StringTokenizer(str," ,.'':\"\"?");
        int count;
        String word;
        while(t.hasMoreTokens()){
            word=t.nextToken();
            if(map.containsKey(word)){
                count=map.get(word);
                map.put(word,++count);
            }
            else{
                map.put(word,1);
            }
        }
        List<Map.Entry<String,Integer>> list=new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list,new Comparator<Map.Entry<String,Integer>>(){
            public int compare(Map.Entry<String,Integer>o1,
                               Map.Entry<String,Integer> o2){
                return o2.getValue()-o1.getValue();
            }
        });
        return map;
    }
    public static void main(String[] args) {
        Scanner input =new Scanner(System.in);
        String str=input.nextLine();
        Map<String,Integer> map=new HashMap<String,Integer>();
        Main T=new Main();
         map=T.task(str);
        System.out.println(map);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值