Collections.frequency: Counting Element Occurrences
What you'll learn: How to use Collections.frequency() to count how many times an element appears in a collection.
The Core Idea
Sometimes you need to know exactly how many times a specific element appears in a collection—maybe to validate input, calculate statistics, or check for duplicates. The Collections.frequency() method does this work for you in a single, efficient call.
Instead of manually iterating through a collection and counting matches yourself, you simply pass the collection and the element you're looking for to frequency(). It returns an integer count.
How It Works
List<String> fruits = List.of("apple", "banana", "apple", "orange", "apple", "banana");
int appleCount = Collections.frequency(fruits, "apple");
int bananaCount = Collections.frequency(fruits, "banana");
int grapeCount = Collections.frequency(fruits, "grape");
System.out.println(appleCount); // 3
System.out.println(bananaCount); // 2
System.out.println(grapeCount); // 0 (not found)
The method works with any Collection (lists, sets, queues) and uses .equals() to compare elements. If the element isn't found, it returns 0.
Common Use Cases
- Validation: Ensure an element appears exactly once or no more than N times
- Statistics: Find the most or least common elements
- Duplicate detection: Check if
frequency() > 1 - Voting systems: Count votes for each option
Analogy
Think of frequency() like asking a librarian, "How many copies of this book do you have?" Instead of counting the shelves yourself, the librarian does it for you and gives you the exact number.
Key Takeaway:
Use Collections.frequency(collection, element) to quickly count how many times any element appears in a collection—it returns 0 if not found and works with any Collection type.