题解 | #简单错误记录#

简单错误记录

https://www.nowcoder.com/practice/2baa6aba39214d6ea91a2e03dff3fbeb

import java.util.Scanner;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Map<ErrorRecord, Integer> map = new LinkedHashMap<>();
        while (in.hasNextLine()) {
            // 重写 ErrorRecord 的 hashcode 和 equals 方法 在map中已经存在了错误记录 则记录数+1 
            map.compute(new ErrorRecord(in.nextLine()), (k, v) -> v == null ? 1 : ++v);
        }
        solution(map);
    }

    public static void solution(Map<ErrorRecord, Integer> map) {
        int cur = 0;
        int size = map.size();
        for (Map.Entry<ErrorRecord, Integer> entry : map.entrySet()) {
            // 打印最后8个
            if (size - cur <= 8) {
                System.out.println(entry.getKey() + " " + entry.getValue());
            }
            cur++;
        }
    }

    private static class ErrorRecord {

        private String name;

        private int line;

        public ErrorRecord(String s) {
            String[] temp = s.split(" ");
            String fileName = temp[0].substring(temp[0].lastIndexOf("\\") + 1);
            this.name = fileName.length() > 16 ? fileName.substring(
                            fileName.length() - 16) : fileName;
            this.line = Integer.parseInt(temp[1]);
        }

        @Override
        public boolean equals(Object er) {
            return name.equals(((ErrorRecord) er).name) && line == ((ErrorRecord) er).line;
        }

        @Override
        public int hashCode() {
            return (this.name + " " + this.line).hashCode();
        }

        @Override
        public String toString() {
            return this.name + " " + this.line;
        }

    }
}

#华为笔试#
全部评论

相关推荐

12-19 19:39
青海大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务