Java Programming Tutorials

Java programming tutorials with many code examples!

Java find/count occurrences


Sometimes you have to in Java find/count occurrences of objects inside a Java Collection. It can be done manually, but vast Java Collections API provides a better way.


Since Java 5 you can count/find frequencies using Collections.frequency(Collection<?> c, Object o) method. It works with different Collections, so you can use List, Set, Map or whatever implements Collection interface.

The following Java code shows how to use it:


import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsFrequency {

    public static void main(String[] args) {
        String s = "Metio lacigas, metio vivigas.";
        List<String> chars = Arrays.asList(s.split(""));

        System.out.println("Original sentence: " + s);
        System.out.println("Chars: " + chars);

        System.out.println("Number of 'M' in chars: "
                + Collections.frequency(chars, "M"));

        System.out.println("Number of 'a' in chars: "
                + Collections.frequency(chars, "a"));

        System.out.println("Number of nulls in chars: "
                + Collections.frequency(chars, null));

Running the code give:

Original sentence: Metio lacigas, metio vivigas.
Chars: [M, e, t, i, o,  , l, a, c, i, g, a, s, ,,  , m, e, t, i, o,  , v, i, v, i, g, a, s, .]
Number of 'M' in chars: 1
Number of 'a' in chars: 3
Number of nulls in chars: 0

You can count/find null too, as you can see in the example. It’s much better to reuse JDK than reinventing the wheel again. ;-)

Was it helpful? Share!