How many times element occurs with frequency()

In a data structure (that accepts duplicate elements), an element can exist any number of times as in the case of ArrayList etc. The frequency() method is useful to find out how many times the same element exist in a data structure.

Following is the method signature

  • static int frequency(Collection col1, Object obj1): Checks how many times obj1 exists in Collection col1; returns as an integer value.
Example on How many times element occurs with frequency()
import java.util.*;
public class CollectionsFrequency
{
  public static void main(String args[])
  {
    ArrayList myList = new ArrayList();
    myList.add(10);
    myList.add(20);
    myList.add(10);
    myList.add(20);
    myList.add(30);
    myList.add(10);
    System.out.println("Elements of ArrayList: " + myList);

    int  num = Collections.frequency(myList, 10);
    System.out.println("\nNo. of times 10 exists: " + num);
    System.out.println("No. of times 20 exists: " + Collections.frequency(myList, 20));
    System.out.println("No. of times 30 exists: " + Collections.frequency(myList, 30));
  }
}


How many times element occurs with frequency()
Output screenshot on How many times element occurs with frequency()

ArrayList myList = new ArrayList();
myList.add(10); myList.add(20);
myList.add(10); myList.add(20);
myList.add(30); myList.add(10);

An ArrayList object myList is created and added with the elements 10 (repeated 3 times), 20 (repeated 2 times) and 30 (occurs only once).

int num = Collections.frequency(myList, 10);
System.out.println(“\nNo. of times 10 exists: ” + num);

The frequency() method returns (as integer value) the number of times element 10 exist in myList. It prints 3 as 10 exists three times.

1 thought on “How many times element occurs with frequency()”

Leave a Comment

Your email address will not be published.