我正在尝试获取 String ArrayList
的重复值的计数,我已经完成了任务,但还没有完全完成。我能够得到 counts
重复项 elements
我的arrayList
,但问题是order
的arrayList
当我得到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/