How many times element occurs with frequency()

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()


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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *