Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

3

All 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:

apple

Common 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

Thanks for reading!

Donate to the site — we work hard for you.