在不影响arrayList顺序的情况下获取Java中arrayList中重复值的计数
Getting the count of duplicate values in arrayList in Java without affecting the order of arrayList
我正在尝试获取 String ArrayList
的重复值计数,我已完成任务但未完成。我能够得到 arrayList
的重复 elements
的 counts
,但问题是 arrayList
的 order
当我得到 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.
我正在尝试获取 String ArrayList
的重复值计数,我已完成任务但未完成。我能够得到 arrayList
的重复 elements
的 counts
,但问题是 arrayList
的 order
当我得到 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.