The frequency()
method of the Collections
class is used to count the number of occurrences of an object in a given collection. Collections
is defined in the util
package in Java, so you must import the util
package before you can use the frequency()
function, as shown below.
import java.util.Collections;
The syntax for frequency()
is shown below.
Collections.frequency(list, object)
public static int frequency(Collection<?> c, Object o)
Collection<?> c
: the collection in which to determine the frequency of o
Object o
: the object whose frequency is to be determinedThe number of elements in Collection c
that are equal to Object o
.
The example below will help you understand the frequency()
function better. We first define an ArrayList
, and use the add()
function to populate the list. Then we use the frequency()
function to get the count of the occurrences of the searchValue
variable.
import java.util.*;public class Main {public static void main(String[] args) {List<String> stringList = new ArrayList<>();stringList.add("a");stringList.add("b");stringList.add("c");stringList.add("d");stringList.add("a");stringList.add("a");stringList.add("a");String searchValue = "a";int count = Collections.frequency(stringList, searchValue);System.out.println("\"" + searchValue + "\" has occurred " + count + " times");}}