ZetCode

Java Collections.frequency Method

Last modified: April 20, 2025

The Collections.frequency method is a utility method provided by Java's Collections framework. It is used to count the number of occurrences of a specific element within a given collection. This method is part of the java.util.Collections class and simplifies tasks such as tallying occurrences in data structures.

The method signature is public static int frequency(Collection<?> c, Object o). It accepts two parameters: a collection and an object to search for. The collection can be any type that implements the Collection interface, such as List, Set, or Queue. The method returns an integer representing the total count of occurrences of the specified object in the collection. If the collection is empty or the specified element is not found, it returns 0.

Basic Usage of Collections.frequency

This example demonstrates the simplest use of Collections.frequency. We create a list of strings and count how many times a specific string appears. The method works with any Collection implementation.

BasicFrequencyExample.java
package com.zetcode;

import java.util.Collections;
import java.util.List;

public class BasicFrequencyExample {

    public static void main(String[] args) {

        List<String> colors = List.of("Red", "Green", "Blue", "Red", "Yellow");

        int redCount = Collections.frequency(colors, "Red");
        int blueCount = Collections.frequency(colors, "Blue");
        int blackCount = Collections.frequency(colors, "Black");

        System.out.println("Red appears " + redCount + " times");
        System.out.println("Blue appears " + blueCount + " times");
        System.out.println("Black appears " + blackCount + " times");
    }
}

This code creates a list of colors with some duplicates. We then use Collections.frequency to count occurrences of "Red", "Blue", and "Black". The method returns 2 for "Red", 1 for "Blue", and 0 for "Black".

The example shows that the method correctly counts existing elements and returns 0 for elements not in the collection. It's case-sensitive and uses equals() for comparison.

Counting Custom Objects

This example demonstrates using Collections.frequency with custom objects. For the method to work correctly, the objects must properly implement the equals method. We'll create a simple Person record and count occurrences.

CustomObjectFrequency.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

record Person(String name, int age) {}

public class CustomObjectFrequency {

    public static void main(String[] args) {

        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 25));
        people.add(new Person("Bob", 30));
        people.add(new Person("Alice", 25));
        people.add(new Person("Charlie", 35));
        people.add(new Person("Alice", 30));

        Person alice25 = new Person("Alice", 25);
        Person alice30 = new Person("Alice", 30);
        Person dave40 = new Person("Dave", 40);

        System.out.println("Alice (25) appears " +
                Collections.frequency(people, alice25) + " times");
        System.out.println("Alice (30) appears " +
                Collections.frequency(people, alice30) + " times");
        System.out.println("Dave (40) appears " +
                Collections.frequency(people, dave40) + " times");
    }
}

This example demonstrates how to count custom objects in a collection using a record. The Person record automatically implements equals, hashCode, and toString methods based on its components (e.g., name and age). This eliminates the need for manual implementation of equals, ensuring proper functionality of Collections.frequency.

We define several Person records and count occurrences of specific instances. The output shows that identical records (same name and age) are correctly counted, while non-matching records return 0. Since the equals method is generated by the record, it plays a vital role in determining object equality.

Frequency with Different Collection Types

The Collections.frequency method works with any Collection implementation. This example demonstrates its use with ArrayList, HashSet, and LinkedList. The behavior remains consistent across different collection types.

DifferentCollectionTypes.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class DifferentCollectionTypes {

    public static void main(String[] args) {
        
        // ArrayList example
        List<Integer> arrayList = new ArrayList<>();
        Collections.addAll(arrayList, 1, 2, 3, 2, 4, 2, 5);
        System.out.println("ArrayList count of 2: " + 
            Collections.frequency(arrayList, 2));
        
        // HashSet example (no duplicates)
        Set<Integer> hashSet = new HashSet<>(arrayList);
        System.out.println("HashSet count of 2: " + 
            Collections.frequency(hashSet, 2));
        
        // LinkedList example
        List<Integer> linkedList = new LinkedList<>();
        Collections.addAll(linkedList, 1, 1, 1, 2, 3);
        System.out.println("LinkedList count of 1: " + 
            Collections.frequency(linkedList, 1));
    }
}

This example shows Collections.frequency working with different collection types. We use an ArrayList with duplicates, a HashSet (which eliminates duplicates), and a LinkedList. The method behaves consistently across all implementations.

The ArrayList shows the count including duplicates (3 for value 2). The HashSet, which cannot contain duplicates, shows either 0 or 1. The LinkedList demonstrates counting in another List implementation.

Frequency with Null Values

This example explores how Collections.frequency handles null values in collections. The method can count null occurrences if the collection contains them. We'll demonstrate this behavior with different scenarios.

NullFrequencyExample.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NullFrequencyExample {

    public static void main(String[] args) {
        
        List<String> words = new ArrayList<>();
        words.add("apple");
        words.add(null);
        words.add("banana");
        words.add(null);
        words.add(null);
        words.add("cherry");
        
        System.out.println("Null appears " + 
            Collections.frequency(words, null) + " times");
        
        System.out.println("\"apple\" appears " + 
            Collections.frequency(words, "apple") + " times");
        
        List<String> noNulls = new ArrayList<>();
        noNulls.add("one");
        noNulls.add("two");
        
        System.out.println("In noNulls, null appears " + 
            Collections.frequency(noNulls, null) + " times");
    }
}

This example demonstrates how Collections.frequency handles null values. We create a list containing several nulls and some strings. The method correctly counts the null occurrences (3 in this case).

We also show that it works normally with non-null values and returns 0 for null counts in collections without nulls. The method safely handles null elements in the collection and null as the search parameter.

Performance Considerations

This example examines the performance characteristics of Collections.frequency. The method performs a linear search, making it O(n) complexity. For large collections, this might impact performance.

FrequencyPerformance.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FrequencyPerformance {

    public static void main(String[] args) {
        
        // Create a large list
        List<Integer> numbers = new ArrayList<>();
        for (int i = 0; i < 1_000_000; i++) {
            numbers.add(i % 100); // Numbers 0-99 repeated
        }
        
        long startTime = System.nanoTime();
        int count = Collections.frequency(numbers, 50);
        long endTime = System.nanoTime();
        
        System.out.println("Count of 50: " + count);
        System.out.println("Time taken: " + 
            (endTime - startTime) / 1_000_000 + " ms");
        
        // Compare with alternative approaches
        startTime = System.nanoTime();
        long streamCount = numbers.stream().filter(n -> n == 50).count();
        endTime = System.nanoTime();
        
        System.out.println("\nStream count of 50: " + streamCount);
        System.out.println("Stream time taken: " + 
            (endTime - startTime) / 1_000_000 + " ms");
    }
}

This example creates a large list and measures the time taken to count occurrences. We compare Collections.frequency with a Java 8 stream approach. Both methods have similar O(n) performance characteristics.

The output shows that for large collections, counting can take noticeable time. If frequency counting is a frequent operation, consider alternative data structures like multisets or maintain separate counters.

Frequency with Multidimensional Collections

This example demonstrates using Collections.frequency with nested collections. The method only counts at the top level - it doesn't recursively search nested collections. We'll show how to handle such cases.

NestedCollectionsFrequency.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NestedCollectionsFrequency {

    public static void main(String[] args) {

        // Declare matrix with generic type
        List<List<Integer> matrix = new ArrayList<>();
        matrix.add(List.of(1, 2, 3));
        matrix.add(List.of(4, 5, 6));
        matrix.add(List.of(1, 2, 3));
        matrix.add(List.of(7, 8, 9));

        // Declare searchList explicitly
        List<Integer> searchList = List.of(1, 2, 3);

        // Use Collections.frequency to count occurrences of searchList in the matrix
        System.out.println("Outer list count: " +
                Collections.frequency(matrix, searchList));

        // To count all occurrences of a specific number in nested lists
        long totalCount = matrix.stream()
                .flatMap(List::stream)
                .filter(n -> n == 2) // Replace "2" with any number to search for
                .count();

        System.out.println("Total count of 2 in all lists: " + totalCount);
    }
}

This example demonstrates how Collections.frequency operates on nested collections. The method counts occurrences of complete inner lists within the outer collection. For example, in this case, it identifies two occurrences of the inner list [1, 2, 3]. However, it does not account for individual elements within the inner lists themselves.

To search within nested collections and count individual elements across all inner lists, we utilize an alternative approach based on streams. By flattening the nested structure using flatMap, we can process and filter elements across all sublists. This approach is essential for scenarios where you need granular control over searching and counting within deeply nested data.

Real-world Example: Word Frequency Counter

This example presents a practical application of Collections.frequency - a simple word frequency counter. We'll read text, split it into words, and count occurrences of specific words.

WordFrequencyCounter.java
package com.zetcode;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class WordFrequencyCounter {

    public static void main(String[] args) {

        String text = """
                The quick brown fox jumps over the lazy dog.
                The quick fox is very quick indeed. The dog is not quick.""";

        // Normalize and split into words
        String[] words = text.toLowerCase().split("\\W+");
        List<String> wordList = List.of(words);

        // Count specific words
        System.out.println("Word frequencies:");
        System.out.println("the: " + Collections.frequency(wordList, "the"));
        System.out.println("quick: " + Collections.frequency(wordList, "quick"));
        System.out.println("fox: " + Collections.frequency(wordList, "fox"));
        System.out.println("dog: " + Collections.frequency(wordList, "dog"));
        System.out.println("lazy: " + Collections.frequency(wordList, "lazy"));

        // Find most frequent word
        String mostFrequent = wordList.stream()
                .distinct()
                .max(Comparator.comparingInt(a -> Collections.frequency(wordList, a)))
                .orElse("");

        System.out.println("\nMost frequent word: " + mostFrequent +
                " (" + Collections.frequency(wordList, mostFrequent) + " times)");
    }
}

This example demonstrates a practical use of Collections.frequency for text analysis. We process a text string into words, then count occurrences of specific words. The example also shows finding the most frequent word.

The code first normalizes the text (converting to lowercase) and splits into words. We then use frequency to count specific words and combine it with streams to find the most frequent word. This shows how frequency can be part of more complex text processing.

Source

Java Collections.frequency Documentation

In this tutorial, we've explored the Java Collections.frequency method in depth. We've covered basic usage, counting custom objects, different collection types, handling null values, performance considerations, nested collections, and a practical word frequency counter application. This method is valuable for efficiently counting element occurrences in any collection type.

Author

My name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts.

List all Java tutorials.