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?

4

5 回答 5

4

这个怎么样:

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
于 2020-01-31T17:20:50.533 回答
4

您可以使用map一个消除多个mapreplaceAll

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

[aeiou]它将匹配内部的任何字符[]并用空字符串替换它

于 2020-01-31T17:22:59.957 回答
2

我将其分解为字符流,仅过滤元音,然后计数:

int tot = l.stream()
  .flatmap(s -> s.chars().stream())
  .filter(c -> c == 'a' || c == 'e' ||c == 'i' ||c == 'o' ||c == 'u')
  .count();
于 2020-01-31T17:22:54.930 回答
1

您可能担心多次replace调用,这与函数式编程无关。替换这些调用的一种方法是使用正则表达式和replaceAll

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

这个单一的地图替换了所有 5 个删除元音的地图。

使用正则表达式,您还可以删除所有非元音。这样,您不必减去tot

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

现在你还有两个连续map的s,你可以把它们合并为一个:

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

这现在更实用了,因为我删除了减法的步骤tot。此操作现在仅描述为函数的组合(就这一抽象级别而言),而不是一堆“步骤”。

于 2020-01-31T17:27:54.127 回答
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));
于 2022-02-02T22:47:48.863 回答