Java.util.Collections.frequency() in Java with Examples

Last Updated : 30 Apr, 2026

The Collections.frequency() method is used to count how many times a specific element appears in a collection. It belongs to the java.util.Collections class and works with any Collection type. The comparison is based on the equals() method.

  • Returns the count of occurrences of a given object
  • Works with any Collection type and supports null values
  • Throws NullPointerException if the collection is null

Syntax:

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

Here,

  • Collection<?> c -> A collection (like List, Set) of any type
  • ? is a wildcard, meaning it can hold any type of objects)
  • Object o → The element whose frequency (count) you want to find
Java
import java.util.*;
 
public class FrequencyDemo
{
    public static void main(String[] args)
    {
        // Let us create a list of strings
        List<String>  mylist = new ArrayList<String>();
        mylist.add("practice");
        mylist.add("code");
        mylist.add("code");
        mylist.add("quiz");
        mylist.add("geeksforgeeks");
 
        // Here we are using frequency() method
        // to get  frequency of element "code"
        int freq = Collections.frequency(mylist, "code");
 
        System.out.println(freq);
    }
}

Output
2

Note: The method can count null elements if the collection contains them and the specified object is also null.

How to Quickly get frequency of an element in an array in Java ?

Arrays class doesn’t have frequency method. But we can use Collections.frequency() to get frequency of an element in an array also.

Note: Primitive values are automatically converted to Integer objects using autoboxing when passed to Collections.frequency().

Java
import java.util.*;
 
public class FrequencyDemo
{
    public static void main(String[] args)
    {
        // Let us create an array of integers
        Integer arr[] = {10, 20, 20, 30, 20, 40, 50};
 
        // Please refer below post for details of asList()
        // https://www.geeksforgeeks.org/java/array-class-in-java/
        int freq = Collections.frequency(Arrays.asList(arr), 20);
 
        System.out.println(freq);
    }
}

Output
3

Comment