Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

collections
frequency
java
communitycreator

What is Collections.frequency() in Java?

abhilash

Overview

The frequency() method of the Collections class is used to count the number of occurrences of an object in a given collection. Collections is defined in the util package in Java, so you must import the util package before you can use the frequency() function, as shown below.

import java.util.Collections;

The syntax for frequency() is shown below.

Collections.frequency(list, object)

Method signature

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

Parameters

  • Collection<?> c: the collection in which to determine the frequency of o
  • Object o: the object whose frequency is to be determined

Return value

The number of elements in Collection c that are equal to Object o.

Example

The example below will help you understand the frequency() function better. We first define an ArrayList, and use the add() function to populate the list. Then we use the frequency() function to get the count of the occurrences of the searchValue variable.

import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        stringList.add("a");
        stringList.add("b");
        stringList.add("c");
        stringList.add("d");
        stringList.add("a");
        stringList.add("a");
        stringList.add("a");
        String searchValue = "a";
        int count = Collections.frequency(stringList, searchValue);
        System.out.println("\"" + searchValue + "\" has occurred " + count + " times");

    }
}

RELATED TAGS

collections
frequency
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring