Collections frequency method

In this post under Java, I will show with example the purpose of “frequency” static method in “Collections” class.

The “frequency” method returns the number of times an element is repeated in a collection.

This method takes two argument
1) the collection it has to search
2) the element for which it has to return the frequency.

Below is the complete main code for your reference.

Main class

1  package core.collection;
2  
3  import java.util.ArrayList;
4  import java.util.Collections;
5  import java.util.List;
6  
7  public class CollectionsFrequencyDemo {
8      public static void main(String[] args) {
9          List<Integer> integerList = new ArrayList<>(0);
10         integerList.add(1);
11         integerList.add(2);
12         integerList.add(2);
13         integerList.add(3);
14         integerList.add(3);
15         integerList.add(3);
16 
17         int count = Collections.frequency(integerList, 2);
18         System.out.println("Frequency of 2: " + count);
19 
20         count = Collections.frequency(integerList, 3);
21         System.out.println("Frequency of 3: " + count);
22     }
23 }

The output will be as shown below

Output

Frequency of 2: 2
Frequency of 3: 3

Leave a comment