How to iterate nested lists with lambda streams?

前端 未结 6 1830
眼角桃花
眼角桃花 2021-02-12 20:16

I\'m trying to refactor the following code to lambda expressions with `stream, especially the nested foreach loops:

public static Result match (Response rsp) {
          


        
6条回答
  •  攒了一身酷
    2021-02-12 20:39

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

提交回复
热议问题