The method is a java.util.Collections class method. It counts the frequency of the specified element in the given list. It override the equals() method to perform the comparison to check if the specified Object and the Object in the list are equal or not.
Syntax:
public static int frequency(Collection c, Object o)
parameters:
c: Collection in which to determine the frequency of o.
o: Object whose frequency is to be determined.
It throws Null Pointer Exception if the Collection c is null.
import java.util.*;
public class GFG
{
public static void main(String[] args)
{
ArrayList<String> list =
new ArrayList<String>();
list.add( "code" );
list.add( "code" );
list.add( "quiz" );
list.add( "code" );
System.out.println( "The frequency of the word code is: " +
Collections.frequency(list, "code" ));
}
}
|
Output:
The frequency of the word code is: 3
Using Java.util. Collections.frequency() for Custom defined objects
The method stated above works well for already defined Objects in java, but what about the custom defined objects. Well, to count the frequency of a custom defined object in java, we will have to simply override the equals() method. Lets see how we can do that.
import java.util.*;
public class GFG
{
public static void main(String[] args)
{
ArrayList<Student> list =
new ArrayList<Student>();
list.add( new Student( "Ram" , 19 ));
list.add( new Student( "Ashok" , 20 ));
list.add( new Student( "Ram" , 19 ));
list.add( new Student( "Ashok" , 19 ));
System.out.println( "The frequency of the Student Ram, 19 is: " +
Collections.frequency(list, new Student( "Ram" , 19 )));
}
}
class Student
{
private String name;
private int age;
Student(String name, int age)
{
this .name=name;
this .age=age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this .name = name;
}
public int getAge()
{
return age;
}
public void setAge( int age)
{
this .age = age;
}
@Override
public boolean equals(Object o)
{
Student s;
if (!(o instanceof Student))
{
return false ;
}
else
{
s=(Student)o;
if ( this .name.equals(s.getName()) && this .age== s.getAge())
{
return true ;
}
}
return false ;
}
}
|
Output:
The frequency of the Student Ram,19 is: 2
This article is contributed by Tanisha Mittal. If you like GeeksforGeeks 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 GeeksforGeeks 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.