gpt4 book ai didi

java - 如何通过函数式编程计算 Java 中的元音?

转载 作者:行者123 更新时间:2023-12-01 10:14:38 24 4
gpt4 key购买 nike

我需要计算 Functional Java 中单词列表中元音的数量。
如果我有这个 list :

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

我的想法是“删除”元音,然后以这种方式进行减法:
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;

有一个更好的方法吗?

最佳答案

这个怎么样:

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

关于java - 如何通过函数式编程计算 Java 中的元音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60008410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com