Home > Java > javaTutorial > How to Count Element Occurrences in a Java ArrayList?

How to Count Element Occurrences in a Java ArrayList?

Susan Sarandon
Release: 2024-12-19 21:23:10
Original
336 people have browsed it

How to Count Element Occurrences in a Java ArrayList?

Counting Element Occurrences in ArrayList

The Java Collection framework provides numerous utilities for manipulating and querying collections. One common task is determining the count of specific elements within a collection. This article explores how to count element occurrences in an ArrayList using the Collections API.

Querying ArrayList Element Count

For the ArrayList in the question:

ArrayList<String> animals = new ArrayList<String>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");
Copy after login

The objective is to count the number of occurrences of the element "bat."

Collections.frequency() API

The Collections class offers a static method called frequency() that returns the count of an element within a collection. This method accepts two parameters, the collection and the element to search for.

int occurrences = Collections.frequency(animals, "bat");
Copy after login

The method will return the count of the element in the collection. In this case, it will return 3, as the ArrayList contains three elements equal to "bat."

This method is available in Java Development Kit (JDK) 1.6 and higher, making it compatible with the product requirements specified in the question.

Conclusion

The Collections.frequency() method provides a straightforward solution for counting the number of occurrences of an element in an ArrayList. This API is simple to use and efficient, offering an effective method for working with collections in Java.

The above is the detailed content of How to Count Element Occurrences in a Java ArrayList?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template