我想重构以下代码以利用 Stream() 方法,但不知道该怎么做。
鉴于变量 sentences 是一个字符串列表,并且预先填充了: “ jack 去了公园”, “玛丽待在家里”, “克里斯去上类了”
我如何使用 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();
}
关于java - 如何重构在字符串列表中搜索文本的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51939004/