0
0
JavaHow-ToBeginner · 3 min read

How to Use Collections.frequency in Java: Simple Guide

Use Collections.frequency(Collection c, Object o) to count how many times an element o appears in the collection c. It returns an int representing the count of the element in the collection.
📐

Syntax

The method signature is:

  • Collections.frequency(Collection c, Object o)

Here:

  • c is the collection where you want to count the element.
  • o is the element whose frequency you want to find.
  • The method returns an int showing how many times o appears in c.
java
int frequency = Collections.frequency(c, o);
💻

Example

This example shows how to count the number of times the string "apple" appears in a list of fruits.

java
import java.util.*;

public class FrequencyExample {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
        int countApple = Collections.frequency(fruits, "apple");
        System.out.println("Number of apples: " + countApple);
    }
}
Output
Number of apples: 3
⚠️

Common Pitfalls

Common mistakes when using Collections.frequency include:

  • Passing null as the collection, which causes NullPointerException.
  • Expecting it to work on arrays directly; it only works on collections like List, Set, etc.
  • Using it with mutable objects without proper equals() method, which can give incorrect counts.

Always ensure the collection is not null and the element's equality is well defined.

java
import java.util.*;

public class PitfallExample {
    public static void main(String[] args) {
        List<String> list = null;
        // This will throw NullPointerException
        // int count = Collections.frequency(list, "apple");

        // Correct way:
        list = Arrays.asList("apple", "banana", "apple");
        int count = Collections.frequency(list, "apple");
        System.out.println("Count: " + count);
    }
}
Output
Count: 2
📊

Quick Reference

MethodDescription
Collections.frequency(Collection c, Object o)Returns how many times element o appears in collection c
Throws NullPointerExceptionIf the collection c is null
Works with any CollectionLike List, Set, etc., but not arrays directly
Uses equals() methodTo compare elements for counting

Key Takeaways

Collections.frequency counts how many times an element appears in a collection.
It requires a non-null Collection and an element to count.
It works with any Collection type but not directly with arrays.
The element's equals() method determines matching for counting.
Avoid passing null collections to prevent exceptions.