How to count occurrences in a list
Short answer
Collections.frequency() counts how many times an element appears in a collection:
void main() {
var votes = List.of("yes", "no", "yes", "yes");
IO.println(Collections.frequency(votes, "yes"));
}Output:
3All elements at once
groupingBy() with counting() builds a "value — count" table:
void main() {
var fruits = List.of("apple", "pear", "apple", "plum", "pear", "apple");
Map<String, Long> counts = fruits.stream()
.collect(Collectors.groupingBy(f -> f, TreeMap::new, Collectors.counting()));
IO.println(counts);
}Output:
{apple=3, pear=2, plum=1}With merge
Without streams: merge() puts 1 for a new key and adds 1 to an existing one:
void main() {
var counts = new TreeMap<String, Integer>();
for (String word : "a b a c b a".split(" ")) {
counts.merge(word, 1, Integer::sum);
}
IO.println(counts);
}Output:
{a=3, b=2, c=1}The most common element
Find the pair with the largest value:
void main() {
var fruits = List.of("apple", "pear", "apple", "plum", "pear", "apple");
String top = fruits.stream()
.collect(Collectors.groupingBy(f -> f, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.orElseThrow()
.getKey();
IO.println(top);
}Output:
appleCommon mistake
Calling Collections.frequency() for every element in a loop. Each call walks the whole list, so on large data the code becomes very slow. To count all elements, build a Map once.
Functions used in this recipe
- Collections.frequency() — Counts how many times an element occurs in a collection.
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
- Collectors.counting() — A counting collector, usually used inside `groupingBy()`.
- Map.merge() — Adds a value under a key or combines it with the existing one.