how to count the number of occurrences of an element in a arraylist in java

how to count the number of occurrences of an element in a arraylist in java

To count the number of occurrences of an element in an ArrayList in Java, you can use the Collections.frequency method of the Collections class.

The Collections.frequency method takes an ArrayList and an element as arguments, and returns the number of occurrences of the element in the ArrayList.

Here is an example of how you can use the Collections.frequency method to count the number of occurrences of an element in an ArrayList in Java:

ref‮ re‬to:lautturi.com
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("apple");

int count = Collections.frequency(list, "apple");
System.out.println("Number of occurrences: " + count);

This code defines an ArrayList called list and adds four elements to it, including two occurrences of the string "apple". It then uses the Collections.frequency method to count the number of occurrences of the string "apple" in the ArrayList, and stores the result in a variable called count. Finally, it prints the number of occurrences to the console.

The output of this code will be:

Number of occurrences: 2

Note that the Collections.frequency method is case-sensitive, so it will treat "apple" and "Apple" as two different elements. If you want to perform a case-insensitive count of the number of occurrences of an element in an ArrayList, you can use a loop to iterate over the elements of the ArrayList and use the equalsIgnoreCase method of the String class to compare the elements.

Here is an example of how you can use a loop and the equalsIgnoreCase method to perform a case-insensitive count of the number of occurrences of an element in an ArrayList in Java:

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("apple");

int count = 0;
for (String s : list) {
  if (s.equalsIgnoreCase("apple")) {
    count++;
  }
}
System.out.println("Number of occurrences: " + count);

This code defines an ArrayList called list and adds four elements to it, including two occurrences of the string "apple". It then uses a for loop to iterate over the elements of the ArrayList, and uses the equalsIgnoreCase method to compare each element to the string "apple". If the element is equal to "apple" (ignoring case), it increments a counter variable called count. Finally, it prints the number of occurrences to the console.

The output of this code will be the same as in the previous example:

Number of occurrences: 2
Created Time:2017-11-01 12:05:15  Author:lautturi