如何重构用于在字符串列表中搜索文本的for循环

时间:2018-08-20 21:57:03

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

我想重构以下代码以利用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);
   }
}

1 个答案:

答案 0 :(得分: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();
}