使用Java Optional.ofNullable有效
问题描述:
我可以提取使用Java8的特定部分像下面使用Java Optional.ofNullable有效
request.getBody()
.getSections()
.filter(section -> "name".equals(section.getName))
.findFirst();
但我怎么在单行使用可选做同样的。我可能有正文或部分为空。
我试过以下,但不工作
Optional.ofNullable(request)
.map(Request::getBody)
.map(Body::getSections)
.filter(section -> "name".equals(section.getName)) //compliation error. section is coming as a list here
.findFirst();
我不能够在一个单一的线得到这个工作。我尝试过使用flatMap,但不能很好地工作。请告知我们是否可以通过单线实现这一目标。
下面是引用
class Request {
Body body;
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
}
class Body {
List<Section> sections;
public List<Section> getSections() {
return sections;
}
public void setSections(List<Section> sections) {
this.sections = sections;
}
}
class Section {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
答
你需要从Optional
表示单个值转换,以一个Stream
与filter
和findFirst()
操作完成完整的模式。至少有一个办法是在任何空的情况下,映射到一个空Stream
(或空List
在邻近的答案):
Optional.ofNullable(request)
.map(Request::getBody)
.map(Body::getSections)
.map(List::stream)
.orElse(Stream.empty())
.filter(section -> "name".equals(section.getName))
.findFirst();
+0
现在我明白了。非常感谢你。 – druid1123
答
这应该为你工作:
Optional.ofNullable(request)
.map(Request::getBody)
.map(Body::getSections)
.orElse(Collections.emptyList())
.stream()
.filter(section -> "name".equals(section.getName))
.findFirst();
更换'.filter (section - >“name”.equals(section.getName))。findFirst();'with'.flatMap(sections - > sections.stream().filter(section - >“name”.equals(section.getName )))。findFirst());' – Holger