我正在尝试将以下代码重构为带有 `stream 的 lambda 表达式,尤其是嵌套的 foreach 循环:
public static Result match (Response rsp) {
Exception lastex = null;
for (FirstNode firstNode : rsp.getFirstNodes()) {
for (SndNode sndNode : firstNode.getSndNodes()) {
try {
if (sndNode.isValid())
return parse(sndNode); //return the first match, retry if fails with ParseException
} catch (ParseException e) {
lastex = e;
}
}
}
//throw the exception if all elements failed
if (lastex != null) {
throw lastex;
}
return null;
}
我从:
rsp.getFirstNodes().forEach().?? // how to iterate the nested 2ndNodes?
最佳答案
看flatMap:
flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
代码示例假设 isValid()
不扔
Optional<SndNode> sndNode = rsp.getFirstNodes()
.stream()
.flatMap(firstNode -> firstNode.getSndNodes().stream()) //This is the key line for merging the nested streams
.filter(sndNode -> sndNode.isValid())
.findFirst();
if (sndNode.isPresent()) {
try {
parse(sndNode.get());
} catch (ParseException e) {
lastex = e;
}
}
关于java - 如何使用 lambda 流迭代嵌套列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29215375/