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

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;
    }
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java中的Comparator接口来实现按照出现次数降序排序。具体实现步骤如下: 1. 创建一个Map,用来统计每个字符串数组中每个字符串出现次数。可以遍历每个字符串数组,同时遍历每个字符串统计出现次数。 2. 创建一个List,将所有字符串数组添加进去。 3. 使用Collections.sort()方法,传入一个Comparator对象,实现按照出现次数降序排序。 4. 在Comparator对象的compare()方法中,比较两个字符串数组出现次数的大小,实现降序排序。 代码实现如下: ``` import java.util.*; public class Main { public static void main(String[] args) { List<String[]> list = new ArrayList<>(); list.add(new String[]{"a", "b", "c", "d", "a", "b"}); list.add(new String[]{"d", "e", "f", "g", "h", "a"}); list.add(new String[]{"a", "b", "c", "d", "e", "f"}); list.add(new String[]{"a", "b", "c", "d", "e", "f", "a", "b", "c"}); // 统计每个字符串出现次数 Map<String, Integer> map = new HashMap<>(); for (String[] strs : list) { for (String str : strs) { map.put(str, map.getOrDefault(str, 0) + 1); } } // 按照出现次数降序排序 Collections.sort(list, new Comparator<String[]>() { @Override public int compare(String[] o1, String[] o2) { int sum1 = 0, sum2 = 0; for (String str : o1) { sum1 += map.get(str); } for (String str : o2) { sum2 += map.get(str); } return sum2 - sum1; } }); // 输出排序结果 for (String[] strs : list) { System.out.println(Arrays.toString(strs)); } } } ``` 输出结果如下: ``` [a, b, c, d, a, b] [a, b, c, d, e, f, a, b, c] [d, e, f, g, h, a] [a, b, c, d, e, f] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值