How to count vowels in Java through functional programming?
Asked Answered
S

5

7

I need to count the number of vowels in a list of words in Functional Java. If I have this list:

List<String> l = Arrays.asList("hello", "world", "test");

My idea was to "delete" the vowels and then do a subtraction this way:

int tot = l.stream().map(s -> s.replace("a", "")).
            map(s -> s.replace("e", "")).
            map(s -> s.replace("i", "")).
            map(s -> s.replace("o", "")).
            map(s -> s.replace("u", "")).
            map(s -> s.length()).reduce(0, Integer::sum);
int res = l.stream().map(s->s.length()).reduce(0, Integer::sum)-tot;

Is there a better way to do this?

Supplication answered 31/1, 2020 at 17:10 Comment(0)
A
4

How about this:

List<String> vowels = Arrays.asList("a", "e", "i", "o", "u");

int count Arrays.stream(string.split(""))  // generate stream from an String[] of single character strings
    .filter(vowels::contains)  // remove all non-vowels
    .count();  // count the elements remaining
Anhydrous answered 31/1, 2020 at 17:20 Comment(0)
G
4

You can eliminate multiple map with one map using replaceAll

    int tot = l.stream()
               .map(s -> s.replaceAll("[aeiou]", "").length())
               .reduce(0, Integer::sum);

[aeiou] it will match any char inside [] and replace it with empty string

Guitarist answered 31/1, 2020 at 17:22 Comment(0)
F
2

I'd break it to stream of chars, filter only vowels and then count:

int tot = l.stream()
  .flatmap(s -> s.chars().stream())
  .filter(c -> c == 'a' || c == 'e' ||c == 'i' ||c == 'o' ||c == 'u')
  .count();
Foist answered 31/1, 2020 at 17:22 Comment(0)
I
1

You're probably concerned about the multiple replace calls, which isn't really related to functional programming. One way to replace those calls is to use a regular expression and replaceAll:

.map(s -> s.replaceAll("[aeiou]", ""))

This single map replaces all 5 maps that removes the vowels.

With a regular expression, you could also remove all the non-vowels. This way, you don't have to subtract tot:

int vowels = l.stream().map(s -> s.replaceAll("[^aeiou]", ""))
                        .map(s -> s.length()).reduce(0, Integer::sum);
// no need to do anything else!

Now you still have two consecutive maps, you can combine them into one:

int vowels = l.stream().map(s -> s.replaceAll("[^aeiou]", "").length())
                        .reduce(0, Integer::sum);

This is now more functional because I've removed the step of subtracting tot. This operation is now described only as a composition of function (as far as this level of abstraction is concerned), instead of a bunch of "steps".

Incubation answered 31/1, 2020 at 17:27 Comment(0)
D
0
Function<String,Integer> vowelsCount = s -> {
        List<Character> vowels = new ArrayList<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
        s = s.toLowerCase();
        int countVowels = 0;
        for (int index = 0; index < s.length(); index++) {
            char currentChar = s.charAt(index);
            if (vowels.contains(currentChar)) {
                countVowels++;
            }
        }
        return countVowels;
    };
    String str = "Lambda expression pattern";
    System.out.printf("%s ==> %d",str, vowelsCount.apply(str));
Drum answered 2/2, 2022 at 22:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.