zoukankan      html  css  js  c++  java
  • 计算一个字符串中每个词的数量并降序输出

    结果:

    代码:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    public class demo {
    
        public static void main(String[] args) throws IOException {
            String S = "马佳;刘胜;马佳;刘胜;慧;慧;刘胜;";
            String str[] = S.split("");
            
            System.out.println(str.length);
            
            Map <String, Integer> map = new HashMap<String, Integer>();
            
            for (String s1 : str) {
                
                if (!map.containsKey(s1))  
                    map.put(s1, 1);  
                else  
                    map.put(s1, (map.get(s1)+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> mapping2, Map.Entry<String, Integer> mapping1) 
                {
                    return mapping1.getValue().compareTo(mapping2.getValue());
                }
            });
         
            Map.Entry<String, Integer> mapping = null;
            for (int i = 0 ;i<list.size() ;i++) {
                mapping = list.get(i);
                if (i<10)
                System.out.println(mapping.getKey() + "=" + mapping.getValue());
            }
        }
    }
  • 相关阅读:
    Python 三级菜单
    linux 下按文件类型删除
    linux 做内网端口映射
    ss
    fio
    libXtst.so.6 is needed by teamviewer-12.0.76279-0.i686
    copy 浅复制 与深复制
    Git 使用方法
    关于 爬虫使用 urllib.urlopen 提交默认 User-Agent值
    Python 官方模块文档
  • 原文地址:https://www.cnblogs.com/mm20/p/11917000.html
Copyright © 2011-2022 走看看