Java Utility Library

Java Collections - frequency() Method



The java.util.Collections.frequency() method returns the number of elements in the specified collection equal to the specified object.

Syntax

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

Parameters

c Specify the collection in which to determine the frequency of o.
o Specify the object whose frequency is to be determined.

Return Value

Returns the number of elements in c equal to o.

Exception

Throws NullPointerException, if c is null.

Example:

In the example below, the java.util.Collections.frequency() method is used to find the number of occurrences of specified element in the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list object
    List<Integer> lst = new ArrayList<Integer>();

    //populating lst
    lst.add(10);
    lst.add(10);
    lst.add(30);
    lst.add(10);
    lst.add(20);
    lst.add(30);   

    //printing the list
    System.out.println("List contains: " + lst); 

    //printing the frequency of given element
    System.out.print("Frequency of 10: ");
    System.out.println(Collections.frequency(lst, 10));
    System.out.print("Frequency of 20: ");
    System.out.println(Collections.frequency(lst, 20));
    System.out.print("Frequency of 30: ");
    System.out.println(Collections.frequency(lst, 30)); 
  }
}

The output of the above code will be:

List contains: [10, 10, 30, 10, 20, 30]
Frequency of 10: 3
Frequency of 20: 1
Frequency of 30: 2

❮ Java.util - Collections