[英]How to count vowels in Java through functional programming?
我需要計算函數式 Java 中單詞列表中元音的數量。 如果我有這個清單:
List<String> l = Arrays.asList("hello", "world", "test");
這個怎么樣:
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
您可以使用replaceAll
用一張map
消除多個map
int tot = l.stream()
.map(s -> s.replaceAll("[aeiou]", "").length())
.reduce(0, Integer::sum);
[aeiou]
它將匹配[]
內的任何字符並將其替換為空字符串
我會將它分解為字符流,僅過濾元音然后計數:
int tot = l.stream()
.flatmap(s -> s.chars().stream())
.filter(c -> c == 'a' || c == 'e' ||c == 'i' ||c == 'o' ||c == 'u')
.count();
您可能擔心多次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
,你可以將它們合二為一:
int vowels = l.stream().map(s -> s.replaceAll("[^aeiou]", "").length())
.reduce(0, Integer::sum);
這現在更實用,因為我刪除了減去tot
的步驟。 這個操作現在只被描述為一個函數的組合(就這個抽象級別而言),而不是一堆“步驟”。
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.