我遇到了 Java 8 流的字符串问题。他们希望我将所有第一个字母更改为大写字母,只要这些单词不属于“the”、“a”、“to”、“of”、“in”组。
我的问题是 filter
命令确实从组中删除了这些单词,而我必须保留它们。
我已经完成了大写第一个字母的部分,但我不知道如何“跳过”这组单词
private List<String> ignoredWords = Arrays.asList("the", "a", "to", "of", "in");
String entryParts[] = toTitlelize.split(" ");
List<String> sentenceParts = Arrays.asList(entryParts);
List<String> finalSentence = sentenceParts.stream()
.map(WordUtils::capitalize)
.collect(toList());
例如:
if toTitlelize = "I love to eat pizza in my home"
它应该返回
"I Love to Eat Pizza in My Home"
目前它给了我:
"I Love To Eat Pizza in My Home"
最佳答案
您可以在映射步骤中使用简单的 if
语句:
List<String> finalSentence = Arrays.stream(entryParts)
.map(word -> {
if (ignoredWords.contains(word)) {
return word;
}
return WordUtils.capitalize(word);
})
.collect(Collectors.toList());
作为替代方案,您可以在 ignoredWords
上使用 filter()
和 findFirst()
并使用 Optional
>:
List<String> finalSentence = Arrays.stream(entryParts)
.map(word -> ignoredWords.stream().filter(w -> w.equals(word)).findFirst().orElse(WordUtils.capitalize(word)))
.collect(Collectors.toList());
我还建议使用 HashSet
而不是 List
,因为单词是唯一的,并且 contains()
更快:
HashSet<String> ignoredWords = new HashSet<>(Arrays.asList("the", "a", "to", "of", "in"));
String.join("", FinalSentence);
的结果将是:
I Love to Eat Pizza in My Home
关于java - 我需要仅对特定单词进行更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55308831/