How to iterate nested lists with lambda streams?

前端 未结 6 1835
眼角桃花
眼角桃花 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:30

    Look at flatMap:

    flatMap(Function> 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.

    Code sample assuming isValid() doesn't throw

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

提交回复
热议问题