统计字符串数组中每个字符出现的次数并按照降序打印输出

2023-12-20 23:42:33
import java.util.*;

public class TestStrStatistics {
    public static void main(String[] args) {
        String[] arr = { "a", "b", "d", "d", "a", "d", "a", "e", "d", "c" };
        HashMap<String,Integer> hashmap = strStatistics(arr);
        ArrayList<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(hashmap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue()-o1.getValue();
            }
        });
        for(Map.Entry<String,Integer> listson:list){
            System.out.println(listson.getKey()+":"+listson.getValue());
        }
    }
    public static HashMap<String,Integer> strStatistics(String[] arr){
        HashMap<String,Integer> hashMap = new HashMap<String,Integer>();
        for(String str:arr){
          if(hashMap.containsKey(str)){
              int valueFrequency = hashMap.get(str);
              hashMap.put(str,++valueFrequency);
          }else {
              hashMap.put(str,1);
          }
        }
       return hashMap;
    }
}

文章来源:https://blog.csdn.net/u014045237/article/details/135096748
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。