EN
Java - count number of element occurrences in ArrayList
0 points
In this article, we would like to show you how to count the number of element occurrences in Arraylist in Java.
Quick solution:
xxxxxxxxxx
1
int occurrences = Collections.frequency(myArrayList, element);
In this example, we use Collections.frequency()
method to count the number of A
elements in letters
ArrayList.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> letters = new ArrayList<>();
7
8
letters.add("A");
9
letters.add("A");
10
letters.add("A");
11
12
int occurrencesA = Collections.frequency(letters, "A");
13
System.out.println("number of A element occurrences: " + occurrencesA);
14
}
15
}
Output:
xxxxxxxxxx
1
number of A element occurrences: 3