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
import java.util.*;
public class FrequencyDemo
{
public static void main(String[] args)
{
List<String> mylist = new ArrayList<String>();
mylist.add( "practice" );
mylist.add( "code" );
mylist.add( "code" );
mylist.add( "quiz" );
mylist.add( "geeksforgeeks" );
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.
import java.util.*;
public class FrequencyDemo
{
public static void main(String[] args)
{
Integer arr[] = { 10 , 20 , 20 , 30 , 20 , 40 , 50 };
int freq = Collections.frequency(Arrays.asList(arr), 20 );
System.out.println(freq);
}
}
|
Output:
3
Last Updated :
07 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...