【编程练习】一段英语段落,统计每个单词有多少个,并按照统计数目倒序。

package jayxigua.coding.pdd._20180508;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 问题描述:一段英语段落,统计每个单词有多少个,并按照统计数目倒序。
 * 技术点:map,entry,集合比较器
 * 难度:★★
 * 歌词提供:http://www.hjenglish.com/new/p1238922/
 * 参考:Map value排序 http://www.cnblogs.com/avivahe/p/5657071.html
 * 
 * @author jayxigua
 *
 */
public class WordsCount {

    public WordsCount() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String input = "Welcome to New York, welcome to New York Welcome to New York, it’s been waiting for you";
        String[] words = input.split(" ");
        System.out.println("words num is " + words.length);
        Map wordMap = new HashMap();
        for (String word : words) {
            Integer count = wordMap.get(word);
            if (count == null) {
                wordMap.put(word, 1);
            } else {
                wordMap.put(word, count + 1);
            }
        }

        List> sortList = new ArrayList>(wordMap.entrySet());

        Collections.sort(sortList, new Comparator>() {
            @Override
            public int compare(Entry o1, Entry o2) {
                // TODO Auto-generated method stub
                return o2.getValue() - o1.getValue();
            }
        });

        for (Entry entry : sortList) {
            System.out.println("word =" + entry.getKey() + ", count=" + entry.getValue());
        }

    }

}

你可能感兴趣的:(【编程练习】一段英语段落,统计每个单词有多少个,并按照统计数目倒序。)