【问题标题】:How to refactor a for loop that search for text in a list of strings如何重构在字符串列表中搜索文本的 for 循环
【发布时间】:2019-01-27 01:42:08
【问题描述】:

我想重构下面的代码以利用 Stream() 方法,但不知道该怎么做。

假设变量 sentence 是一个字符串列表,并且预先填充了: “杰克去了公园”, “玛丽待在家里”, “克里斯去上班了”

如何使用 Stream() 来返回包含单词“home”的整行

List<String> sentences = new ArrayList<>();
sentences.add("Jack went to the park");
sentences.add("Mary stayed home");
sentences.add("Chris went to work");

for (int I=0; I < sentences.size(); I++) {
   if (sentences.get(I).contains("home")) {
      return sentences.get(I);
   }
}

【问题讨论】:

    标签: java for-loop arraylist refactoring java-stream


    【解决方案1】:
    sentences.stream()
        .filter(str -> str.contains("home"))
        .findAny()
        .orElse("String to return if string which contains home was not found");`
    

    或者你可以查看Optional的结果,这段代码和你的完全一样:

    Optional<String> result = sentences.stream()
        .filter(str -> str.contains("home"))
        .findAny()
    
    if (result.isPresent()) {
        return result.get();
    }
    

    【讨论】:

    • 感谢 Chmilevfa 提供两个答案。我试图使用 lambda,但无法让它工作。
    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2014-10-11
    • 2021-10-11
    • 1970-01-01
    相关资源
    最近更新 更多