I\'m trying to refactor the following code to lambda expressions with `stream, especially the nested foreach loops:
public static Result match (Response rsp) {
A little bit late but here is a readable approach:
Result = rsp.getFirstNodes()
.stream()
.flatMap(firstNode -> firstNode.getSndNodes.stream())
.filter(secondNode::isValid))
.findFirst()
.map(node -> this.parseNode(node)).orElse(null);
Explanation: you get all the firstNodes
and stream()
them up. Out a each firstNode you bring n SndNodes
. You check each SndNodes
to see find the first one that is valid. If there is no valid SndNode then we'll get a null. If there is one, it'll get parsed into a Result
the parseMethod() doesn't change from the original:
public Result parseNode(SndNode node){
try {
...
... // attempt to parsed node
} catch (ParseException e) {
throw new ParseException;
}
}