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

How to Efficiently Count Element Occurrences in a Java ArrayList?

Susan Sarandon
Release: 2024-12-13 13:17:10
Original
684 people have browsed it

How to Efficiently Count Element Occurrences in a Java ArrayList?

Counting Occurrences of Elements in Lists: A Java Solution

In Java's ArrayList implementation, a collection class, counting the number of occurrences of specific elements can be crucial. Consider the example below:

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

Here, the animals ArrayList includes three occurrences of "bat" and one of "owl." This raises the question of how to determine the count of "bat" occurrences in the ArrayList without relying on Google's Collection Multiset, which is not compatible with JDK 1.6.

Solution:

The Java Collections framework provides a concise solution for this scenario through its static frequency method:

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

Utilizing this method, we can effortlessly ascertain the number of occurrences for any desired element within the ArrayList. In this specific example, the result stored in occurrences would be 3. The Collections.frequency method proves to be a versatile tool for this common programming task.

The above is the detailed content of How to Efficiently 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