Collections.frequency() in Java

Java's Collections class provides a frequency() method that returns the number of times an element appears in a Collection. This method works for collections that implement the Collection interface, such as ArrayList, LinkedList, ArrayDeque, etc.

The method's declaration is:

java
public static int frequency(Collection<?> c, Object o)

Where c is the collection in which to determine the frequency of o, and o is the object whose frequency is to be determined.

The method returns the number of elements in the specified collection equal to the specified object.

Let's look at a few examples to see how the frequency() method works:

Example 1:

csharp
import java.util.*; public class Example1 { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(10); // Count the frequency of 10 System.out.println(Collections.frequency(list, 10)); } }

Output:

2

Example 2:

java
import java.util.*; class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Point)) return false; Point p = (Point)o; return p.x == x && p.y == y; } } public class Example2 { public static void main(String[] args) { List<Point> list = new ArrayList<Point>(); // Adding element to list list.add(new Point(10, 20)); list.add(new Point(5, 25)); list.add(new Point(10, 20)); Point p = new Point(10, 20); int freq = Collections.frequency(list, p); // prining the frequency System.out.println(freq); } }

Output:

2

In Example 2, we are using a user-defined type Point and overriding the equals() method to ensure that the frequency() method can properly compare the elements in the list.

Example 3:

java
import java.util.*; class Example3 { public static void main(String[] args) { Integer arr[] = {10, 15, 10, 20}; // asList() creates a wrapper over the same array and converts the // array to a list int res = Collections.frequency(Arrays.asList(arr), 10); // Count the frequency of 10 System.out.println(res); } }

Output:

2

In Example 3, we are using an array of Integers and converting it to a List using the asList() method before calling the frequency() method.

Overall, the Collections.frequency() method is a useful tool for determining the frequency of elements in a collection, and can be used with both built-in and user-defined types.

Previous Post Next Post