If you need both values ββand you want to use flatMap (as required when you want to perform a short circuit operation, for example findFirst ), you need to map an object containing both values
response.getFirstNodes().stream() .flatMap(first->first.getSndNodes().stream() .map(snd->new AbstractMap.SimpleImmutableEntry<>(first, snd))) .filter(e->e.getValue().isValid()) .findFirst().ifPresent(e-> { result.setKey(e.getKey().getKey()); result.setContent(e.getValue().getContent()); });
To use only the standard classes, I use the Map.Entry type as a pair, while the actual type of the pair may look more concise.
In this particular use case, you can move the filter operation to the internal thread
response.getFirstNodes().stream() .flatMap(first->first.getSndNodes().stream() .filter(snd->snd.isValid()) .map(snd->new AbstractMap.SimpleImmutableEntry<>(first, snd))) .findFirst().ifPresent(e-> { result.setKey(e.getKey().getKey()); result.setContent(e.getValue().getContent()); });
which has a neat effect for only one matching element, an instance of Map.Entry will be created (well, as the current implementation is not as lazy as it should , but even then it will create smaller objects than in the first version).
source share