How to iterate nested for loops referring to parent elements using Java 8 streams?

前端 未结 2 570
青春惊慌失措
青春惊慌失措 2021-02-06 04:25

I want to iterate nested lists using java8 streams, and extract some results of the lists on first match. Unfortunately I have to also get a values from the parent

2条回答
  •  你的背包
    2021-02-06 04:26

    It should be like this:

    Edit: Thanks Holger for pointing out that the code won't stop at the first valid FirstNode

    response.getFirstNodes().stream()
      .filter(it -> {it.getSndNodes().stream().filter(SndNode::isValid).findFirst(); return true;})
      .findFirst()
      .ifPresent(first -> first.getSndNodes().stream().filter(SndNode::isValid).findFirst().ifPresent(snd -> {
        result.setKey(first.getKey());
        result.setContent(snd.getContent());
      }));
    

    A test can be found here

提交回复
热议问题