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

标签 java arraylist hashmap find-occurrences

我正在尝试获取 String ArrayList 的重复值的计数,我已经完成了任务,但还没有完全完成。我能够得到 counts重复项 elements我的arrayList ,但问题是orderarrayList当我得到occurrences时破坏的elements

这是我的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());
    }

此代码可以很好地获取 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.

关于java - Java中获取arrayList中重复值的计数而不影响arrayList的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41380274/

相关文章:

java - 在 Linux 命令行上从 JAR 执行 Java 类

Java 文本区域中的流水号

java - Arraylist 将值相乘在一起未按预期执行

java - 检查 Map 中是否存在键后,拆箱可能会产生空指针异常

java - 填写 Freemarker 模板上的组合框

java - Jacoco SonarQube 集成

java - 从共享首选项中以有序方式保存和检索 ArrayList<String>

java - 如何复制一个不受原始ArrayList更改影响的ArrayList?

loops - 是否有 Raku 函数/方法允许迭代排序的哈希数组并确定其最大值?

java - 将国家列表中的国家一一分配给PlayerList中的玩家