In this guide, you will learn about the Collections frequency() method in Java programming and how to use it with an example.
1. Collections frequency() Method Overview
Definition:
The frequency() method of the Collections class in Java is used to get the number of occurrences of a specified element in a collection.
Syntax:
Collections.frequency(Collection<?> c, Object o)
Parameters:
- c: The collection in which to determine the frequency of o.
- o: The element whose frequency is to be determined.
Key Points:
- If the collection contains multiple instances of the specified element, this method counts all of them.
- If the specified collection is null or if the specified element is null and the collection doesn't permit null elements, the method will throw a NullPointerException.
- The method uses the equals method to check for the presence of the element.
- This is a simple method to quickly check the frequency of an item in a collection without needing to iterate through the collection manually.
2. Collections frequency() Method Example
import java.util.*;
public class CollectionsFrequencyExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple"));
// Counting occurrences of 'apple'
int appleCount = Collections.frequency(fruits, "apple");
System.out.println("Occurrences of apple: " + appleCount);
// Counting occurrences of 'mango' which is not in the list
int mangoCount = Collections.frequency(fruits, "mango");
System.out.println("Occurrences of mango: " + mangoCount);
}
}
Output:
Occurrences of apple: 3 Occurrences of mango: 0
Explanation:
In the example, we have a list of fruits with repeated occurrences of "apple" and "banana".
We utilize the frequency() method to determine the count of "apple" in the list, which is 3.
We then attempt to determine the frequency of "mango", which is not present in the list. As a result, the method returns 0, indicating that "mango" does not appear in the list.
Comments
Post a Comment
Leave Comment