統計 List 中各元素出現次數。JDK 1.5+ 提供 Collections.frequency(),亦可手動用 Map 計數。
List list = new ArrayList<>();
list.add("a"); list.add("b"); list.add("c"); list.add("d");
list.add("b"); list.add("c"); list.add("a"); list.add("a"); list.add("a");
// 結果:a:4, b:2, c:2, d:1
System.out.println("a 出現次數: " + Collections.frequency(list, "a")); // 4
Set unique = new HashSet<>(list);
for (String s : unique) {
System.out.println(s + ": " + Collections.frequency(list, s));
}
缺點:每次調用需遍歷整個 List,時間複雜度 O(n²),大數據量性能差。
Map map = new HashMap<>();
for (String s : list) {
Integer count = map.get(s);
map.put(s, (count == null) ? 1 : count + 1);
}
// 輸出
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key-value: " + entry.getKey() + " - " + entry.getValue());
}
Map sortedMap = new TreeMap<>(map); // 自然順序排序
for (Map.Entry entry : sortedMap.entrySet()) {
System.out.println("Key-value: " + entry.getKey() + " - " + entry.getValue());
}
例子1 - 計算'a'出現的次數
a : 4
例子2 - 計算所有對象出現的次數
d: 1
b: 2
c: 2
a: 4
例子3 - 用Map來計算對象出現的次數
Key-value : d - 1
Key-value : b - 2
Key-value : c - 2
Key-value : a - 4
Map排序-以key排序
Key-value : a - 4
Key-value : b - 2
Key-value : c - 2
Key-value : d - 1
Collections.frequency 代碼簡潔可接受list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()))