Java Dailly Tip: How to find the number of vowels in the String ArrayList

Java Dailly Tip: How to find the number of vowels in the String ArrayList

Problem

I have a word list and a vowel list. How can I select from the list only words that contain the selected vowels? I would like some solutions.

Solution

Meaning if you have for example 3 vowels in your String, contains will just return true, it does not actually count them.

public static int numberOfV(List VList, String vowel){
     int sum = 0;
       
     for(String s : Vlist){
         //iterate each string, check all characters!
         for(char c: s.toCharArray()) {
            if(String.valueOf(c).equals(vowel)) {
                //we found one of this vowel
                sum++;
            }
         }
     }
     return sum;
}

When you are dealing with characters ("letters"), it might be more appropriate to use char type instead of String.

Another solution is to use stream:

public static int numberOfV(List VList, String vowel){
    return VList.stream()
      .map(s -> s.replaceAll("[^" + vowel + "]", ""))
      .mapToInt(String::length)
      .sum();
}

Share this Post