我想重构以下代码以利用Stream()方法,但不知道如何做到这一点。

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

我将如何使用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);
   }
}

最佳答案

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();
}

09-12 16:25