每日一练:一直两个字符串A,B。 连续进行读入n次。 每次读入的字符串都为A|B。 输出读入次数最多的字符串。各位有什么好方法,欢迎交流

public static void main(String[] args) throws Exception{
        Scanner scan = new Scanner(System.in);
        String str_0 = scan.nextLine().trim();
        int n = Integer.parseInt(str_0);
        ArrayList<String> vector = new ArrayList<>();
        for (int i = 0; i < n; i++){
            String str_1 = scan.nextLine().trim();
            vector.add(str_1);
        }
        scan.close();
        String result = solution(n, vector);
        System.out.println(result);
    }
public static String solution(int n, ArrayList<String> vector){
        String result = "";
        HashMap<String, Integer> map = new HashMap<>();
        // 循环计数每个字符串出现的次数
        for(String c:vector){
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }else {
                map.put(c,1);
            }
        }
        List<Map.Entry<String,Integer>> list = new ArrayList(map.entrySet());
        // 根据字符串出现的次数排序
        // Collections.sort(list,(o1, o2) ->(o1.getValue()-o2.getValue()));
        Collections.sort(list, Comparator.comparingInt(Map.Entry::getValue));
        int size = list.size();
        if(list.get(size-1).getValue() == list.get(size-2).getValue()){
            result = "dogfall";
        }else {
            result = list.get(size-1).getKey();
        }
        return result;
    }
// 总是提示把下面的代码替换成为另一种写法
Collections.sort(list,(o1, o2) ->(o1.getValue()-o2.getValue()));


Collections.sort(list, Comparator.comparingInt(Map.Entry::getValue));

 提示信息:返回与此条目对应的值。如果映射已从支持映射中移除(通过迭代器的移除操作),则此调用的结果是未定义的。(第一种写法的问题 应该就是说如果排序后有remove操作,会报索引越界异常)

运行结果截图

平局: 

        

示例: 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值