当您需要两个值并且想要使用flatMap时(根据需要执行像findFirst这样的短路操作时),您必须映射到包含两个值的对象
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());
});
为了仅使用标准类,我使用Map.Entry作为Pair类型,而真正的Pair类型可能看起来更简洁.
在此特定用例中,您可以将筛选器操作移动到内部流
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());
});
它具有整洁的效果,只有一个匹配的项目,一个Map.Entry实例将被创建(好吧,应该作为the current implementation is not as lazy as it should,但即便如此,它仍然会创建比第一个变体更少的对象).