Simple Error Logging - HashMap and LinkedHashMap

In the process of brushing the questions recently, I encountered a small problem in using HashMap to sort files.

topic:

开发一个简单错误记录功能小模块,能够记录出错的代码所在的文件名称和行号。 
处理:
1.记录最多8条错误记录,对相同的错误记录(即文件名称和行号完全匹配)只记录一条,错误计数增加;(文件所在的目录不同,文件名和行号相同也要合并)
2.超过16个字符的文件名称,只记录文件的最后有效16个字符;(如果文件名不同,而只是文件名的后16个字符和行号相同,也不要合并)
3.输入的文件可能带路径,记录文件名称不能带路径

输入描述:
一行或多行字符串。每行包括带路径文件名称,行号,以空格隔开。

    文件路径为windows格式

    如:E:\V1R2\product\fpgadrive.c 1325


输出描述:
将所有的记录统计并将结果输出,格式:文件名代码行数数目,一个空格隔开,如: fpgadrive.c 1325 1 

    结果根据数目从多到少排序,数目相同的情况下,按照输入第一次出现顺序排序。

    如果超过8条记录,则只输出前8条记录.

    如果文件名的长度超过16个字符,则只输出后16个字符

输入例子1:
E:\V1R2\product\fpgadrive.c 1325

输出例子1:
fpgadrive.c 1325 1

own code:

When using HashMap, the submission fails, but when using LinkedHashMap, the submission passes.

public static  void main(String []args) {
        Scanner sr = new Scanner(System.in);
        HashMap<String, Integer> map = new HashMap<>();  //LinkedHashMap
        do {

            String str = sr.next();
            int index = sr.nextInt();
            int in  = str.lastIndexOf('\\');
            str = str.substring(in+1, str.length()) + " " + index;
            if (map.containsKey(str)) {
                map.put(str, map.get(str) + 1);
            } else {
                map.put(str, 1);
            }

        } while (sr.hasNext());
        sr.close();
        //对记录排序
        //对记录进行排序
        List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            //降序
            @Override
            public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) {
                return (arg1.getValue() - arg0.getValue()) == 0 ? (arg0.getValue() - arg1.getValue()) : (arg1.getValue() - arg0.getValue());
            }
        });
        //只输出前8条
        int m = 0;
        for (Map.Entry<String, Integer> mapping : list) {
            m++;
            if (m <= 8) {
                String[] str = mapping.getKey().split(" ");
                String k = str[0].length() > 16 ? str[0].substring(str[0].length() - 16) : str[0];
                String n = str[1];
                System.out.println(k + " " + n + " " + mapping.getValue());
            } else {
                break;
            }
        }
    }

HashMap output result:

write picture description here

Summary analysis: The characteristic of LinkedHashmap is that the position of the object put in does not change, while the HashMap will change.

Java defines an interface java.util.Map for mapping in the data structure; it has four implementation classes, namely HashMap Hashtable LinkedHashMap and TreeMap.

Map is mainly used to store key-value pairs, and get the value according to the key, so the key is not allowed to be repeated (duplicated and overwritten), but the value is allowed to be repeated.
Hashmap is one of the most commonly used Maps, which stores data according to the HashCode value of the key (repeated storage of the same hashCode will not cause an error, but only one value will be retained, the rules of equals and hashCode, different hashCode may equals. But not equals must have different hashCode), its value can be obtained directly according to the key, and it has a fast access speed. When traversing, the order of obtaining data is completely random .

HashMap only allows the key of one record to be Null at most; allows the value of multiple records to be Null;

HashMap arranges the stored data in ascending order of keys by default, so it will affect the performance to a certain extent.

HashMap does not support thread synchronization, that is, multiple threads can write HashMap at the same time at any time; it may cause data inconsistency.

If synchronization is required, the synchronizedMap method of Collections can be used to enable HashMap to be synchronized, or ConcurrentHashMap can be used; however, performance will be affected in this case.

Hashtable is similar to HashMap, it inherits from Dictionary class, the difference is: it does not allow the key or value of records to be empty; it supports thread synchronization, that is, only one thread can write Hashtable at any time, so it also causes Hashtable to write Entry will be slower.

LinkedHashMap is a subclass of HashMap, which saves the insertion order of records. When using Iterator to traverse LinkedHashMap, the first record must be inserted first (first-in, first-out, similar to stack). You can also use parameters during construction, according to Sort by number of applications . It will be slower than HashMap when traversing (because linkedhashmap needs to save the order of insertion, which requires extra overhead) , but there is an exception. When HashMap has a large capacity and actual data is small, it may be slower than LinkedHashMap to traverse, because LinkedHashMap The traversal speed of HashMap is only related to the actual data and has nothing to do with the capacity, while the traversal speed of HashMap is related to its capacity.

TreeMap implements the SortMap interface, which can sort the records it saves according to the key. The default is to sort in ascending order of the key value. You can also specify the sort comparator. When iterator is used to traverse the TreeMap, the obtained records are sorted.

In general, we use HashMap the most. To insert, delete and locate elements in Map, HashMap is the best choice. But if you want to iterate over keys in natural order or custom order then TreeMap is better. If the order of the output is required to be the same as that of the input, then LinkedHashMap can be used, and it can also be arranged in the order of reading.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324531167&siteId=291194637