面试题-排序:统计一篇文章中单词出现的次数

package example;

import java.util.*;

/**
 * Created by TR_VMHyper on 2016/8/17.
 */
public class Test {
    public static void main(String[]args){
        /**
         * 面试题:统计一篇文章中出现单词出现的次数
         */
        String str="Do be a good student and also to be a good boy . The beautiful girl i hope to marry with you . It's my dream. Dream for dream ...";
        String[]sts=str.split(" ");
        Map<String,Integer> map=new HashMap<String,Integer>();
        for (String s : sts) {
            if (map.containsKey(s.toLowerCase())){
                map.put(s.toLowerCase(),map.get(s.toLowerCase())+1);
            }else{
                map.put(s.toLowerCase(),1);
            }
        }
        int max=0;
        //System.out.println(map.entrySet());
        Set<Map.Entry<String,Integer>>ks= map.entrySet();
        List<Map.Entry<String,Integer>>ins=new ArrayList<Map.Entry<String,Integer>>(ks);
        Collections.sort(ins, new Comparator<Map.Entry<String,Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if (o1.getValue()<o2.getValue()){
                    return -1;
                }else if (o1.getValue()>o2.getValue()){
                    return 1;
                }
                return 0;
            }
        });
        System.out.println(ins);
        //System.out.print(ins.get(ins.size()-1));
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,906评论 18 399
  • 第十天 权限修饰符 public protected default private 同一类 true true ...
    炙冰阅读 3,561评论 0 1
  • 一、 1、请用Java写一个冒泡排序方法 【参考答案】 public static void Bubble(int...
    独云阅读 5,242评论 0 6
  • java笔记第一天 == 和 equals ==比较的比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量...
    jmychou阅读 5,386评论 0 3
  • 这是古典老师在“得到”APP上开设的《超级个体》专栏的学习总结,第一周,主题是“未来5年的职场趋势”。 1.未来职...
    听早雨阅读 3,904评论 0 1