Java Collections frequency() Method
Example
Count how many times "Volvo" appears in a list:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Volvo");
cars.add("Ford");
System.out.println(Collections.frequency(cars, "Volvo"));
}
}
Definition and Usage
The frequency() method counts how many items in a collection are equal to the given value.
It uses the equals() method to compare the items.
Syntax
public static int frequency(Collection c, Object item)
Parameter Values
| Parameter | Description |
|---|---|
| c | Required. The collection to search in. |
| item | Required. The value to count. |
Technical Details
| Returns: | The number of items in the collection that are equal to item. |
|---|
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods