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

362 views Asked by At

I am trying to get the count of duplicate values of String ArrayList, i have achieved the task but not completely. i am able to get the counts of duplicate elements of my arrayList, but the problem is that the order of arrayList destroys when i get the occurrences of elements

here is my code:

    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());
    }

this code works fine for getting occurrences but note that this code destroys the order. what i want is that the order should also not be destroyed.

1

There are 1 answers

1
sidgate On BEST ANSWER

Use LinkedHashMap instead of HashMap to preserve the insertion order

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.