mem*_*und 8 java optional java-8 java-stream
我想使用java8迭代嵌套列表streams,并在第一次匹配时提取列表的一些结果.不幸的是,如果子元素与过滤器匹配,我还必须从父内容中获取值.
我怎么能这样做?
// java7
Result result = new Result();
//find first match and pupulate the result object.
for (FirstNode first : response.getFirstNodes()) {
for (SndNode snd : first.getSndNodes()) {
if (snd.isValid()) {
result.setKey(first.getKey());
result.setContent(snd.getContent());
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
// java8
response.getFirstNodes().stream()
.flatMap(first -> first.getSndNodes())
.filter(snd -> snd.isValid())
.findFirst()
.ifPresent(???); //cannot access snd.getContent() here
Run Code Online (Sandbox Code Playgroud)
Hol*_*ger 12
当您需要两个值并且想要使用时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());
});
Run Code Online (Sandbox Code Playgroud)
为了仅使用标准类,我使用一个Map.EntryPair类型,而一个真正的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());
});
Run Code Online (Sandbox Code Playgroud)
它具有整洁的效果,只有一个匹配的项目,Map.Entry才会创建一个实例(好吧,应该因为当前的实现并不像它应该的那样懒,但即使这样,它仍然会创建比第一个变体更少的对象).
| 归档时间: |
|
| 查看次数: |
3618 次 |
| 最近记录: |