How to count the number of occurrences of an element in a List
To count the number of occurrences of an element in a List
in Java, you can use the Collections.frequency(Collection, Object)
method, which returns the number of times the specified element appears in the collection.
For example, suppose you have a List
of strings called myList
and you want to count the number of occurrences of the string "apple":
import java.util.Collections;
import java.util.List;
public class CountOccurrencesExample {
public static void main(String[] args) {
List<String> myList = Arrays.asList("apple", "banana", "apple", "orange", "apple");
int count = Collections.frequency(myList, "apple");
System.out.println(count);
}
}
This example will print the number 3
, since "apple" appears three times in the list.
Alternatively, you can use a loop to iterate through the list and count the occurrences manually:
int count = 0;
for (String s : myList) {
if (s.equals("apple")) {
count++;
}
}
I hope this helps. Let me know if you have any questions.