【问题标题】:I need to do changes just on specific words我需要对特定的词进行更改
【发布时间】:2019-03-22 22:59:32
【问题描述】:

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"

它应该返回

“我喜欢在家吃披萨”

目前它给了我:

“我喜欢在家吃披萨”

【问题讨论】:

  • 您可以选择实现capitalize,使其也忽略来自ignoredWords 集合的单词。

标签: java filter java-stream


【解决方案1】:

您可以在映射步骤中使用简单的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); 的结果将是:

我喜欢在家吃披萨

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2023-02-09
    • 2016-12-29
    相关资源
    最近更新 更多