Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collections.frequency()

Counts how many times an element occurs in a collection.

Available since: Java 1.5

Syntax

static int frequency(Collection<?> c, Object o)

Parameters

ParameterTypeDescription
cCollection<?>The collection to count in.
oObjectThe element to count.

Return value

intHow many times the element occurs in the collection.

Examples

How many times a value occurs:

void main() {
    List<String> answers = List.of("yes", "no", "yes", "yes", "maybe");
    IO.println(Collections.frequency(answers, "yes"));
    IO.println(Collections.frequency(answers, "never"));
}

Output:

3
0

Notes

Each call scans the whole collection. To count the frequencies of all values at once, use Collectors.groupingBy(..., Collectors.counting()) or map.merge().

See also

Related recipes

In the tutorial

  • Collection helper methods — The Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.

Thanks for reading!

Donate to the site — we work hard for you.