To count the number of occurrences of a specific element in a list in Java, you can use a loop to iterate through the list and increment a counter variable when the element matches the desired one.
In this example,
numbers
containing integer elements.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(1);
numbers.add(2);
numbers.add(1);
int count = 0;
for (int num : numbers) {
if (num == 1) {
count++;
}
}
System.out.println("Count of 1 is: " + count);
}
}
Count of 1 is: 3
In this example,
words
containing string elements.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<>();
words.add("apple");
words.add("banana");
words.add("apple");
words.add("cherry");
int count = 0;
for (String word : words) {
if (word.equals("apple")) {
count++;
}
}
System.out.println("Count of 'apple' is: " + count);
}
}
Count of 'apple' is: 2
In this tutorial, we learned How to count the Number of Occurrences of Specific Element in the List in Java language with well detailed examples.