Count the number of elements equal to a specified object in a Collection.
The Collections.frequency() method returns the number of elements in the specified collection equal to the specified object. It uses the equals() method for comparison, and null is a valid argument (it counts null elements).
This method iterates over the entire collection, resulting in O(n) time complexity. For frequent lookups, consider using a Map to count elements or a Multiset from a library like Guava.
This is useful for counting occurrences in lists, checking for duplicates, and performing frequency analysis on collections of data.
| Name | Description | Optional |
|---|---|---|
c |
The collection in which to count occurrences. | No |
o |
The object whose frequency is to be determined. | No |
List<String> list = Arrays.asList("a", "b", "a", "c", "a");
Collections.frequency(list, "a"); // 3
Collections.frequency(list, "d"); // 0