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
| Parameter | Type | Description |
|---|---|---|
| c | Collection<?> | The collection to count in. |
| o | Object | The 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
0Notes
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
- Collectors.counting() — A counting collector, usually used inside `groupingBy()`.
- Map.merge() — Adds a value under a key or combines it with the existing one.
- List.contains() — Checks whether a list contains an element.
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.