在Java中获取arrayList中重复值的计数而不影响arrayList的顺序

Getting the count of duplicate values in arrayList in Java without affecting the order of arrayList

本问题已经有最佳答案,请猛点这里访问。

我试图得到String ArrayList的重复值的计数,我已经完成了任务但不完全。 我能够得到arrayList的重复elementscounts,但问题是当我得到elements arrayList时,arrayListorder会破坏

这是我的code

1
2
3
4
5
6
7
8
9
10
11
12
13
    Map<String, Integer> counts = new HashMap<String, Integer>();

    for (String str : t.courseName) {
        if (counts.containsKey(str)) {
            counts.put(str, counts.get(str) + 1);
        } else {
            counts.put(str, 1);
        }
    }

    for (Map.Entry<String, Integer> entry : counts.entrySet()) {
        System.out.println(entry.getKey() +" =" + entry.getValue());
    }

获取occurrences时此代码可以正常工作,但请注意,此代码会破坏order。 我想要的是order也不应该被销毁。


使用LinkedHashMap而不是HashMap来保留插入顺序

A LinkedHashMap is a combination of hash table and linked list. It has a predictable iteration order (a la linked list), yet the retrieval speed is that of a HashMap. The order of the iteration is determined by the insertion order, so you will get the key/values back in the order that they were added to this Map.