Friday, September 26, 2025
HomeLanguagesJavaJava.util.Collections.frequency() in Java with Examples

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

java.util.Collections.frequency() method is present in java.util.Collections class. It is used to get the frequency of a element present in the specified list of Collection. More formally, it returns the number of elements e in the collection.

Syntax

public static int frequency(Collection<?> c, Object o)
Parameters : 
c - the collection in which to determine the frequency of o
o - the object whose frequency is to be determined
Returns :
Returns the number of elements in the specified collection 
equal to the specified object.
Throws:
NullPointerException - if c is null




// Java program to demonstrate working of 
// java.utils.Collections.frequency()
  
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("neveropen");
   
        // Here we are using frequency() method
        // to get  frequency of element "code"
        int freq = Collections.frequency(mylist, "code");
   
        System.out.println(freq);
    }
}


Output:

2

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

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




// Java program to get frequency of an element 
//  with java.utils.Collections.frequency()
  
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()
        int freq = Collections.frequency(Arrays.asList(arr), 20);
   
        System.out.println(freq);
    }
}


Output:

3

This article is contributed by Gaurav Miglani. If you like Lazyroar and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32321 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6689 POSTS0 COMMENTS
Nicole Veronica
11857 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6801 POSTS0 COMMENTS
Ted Musemwa
7072 POSTS0 COMMENTS
Thapelo Manthata
6761 POSTS0 COMMENTS
Umr Jansen
6766 POSTS0 COMMENTS