有效地使用Java Optional.ofNullable
我可以使用Java8提取一个特定的部分,如下所示有效地使用Java Optional.ofNullable,java,java-8,optional,Java,Java 8,Optional,我可以使用Java8提取一个特定的部分,如下所示 request.getBody() .getSections() .filter(section -> "name".equals(section.getName)) .findFirst(); 但是如何在单行中使用optional执行相同操作呢。我的正文或节可能为空 我试过下面的方法,但不起作用 Optional.ofNullable(request) .map(Request:
request.getBody()
.getSections()
.filter(section -> "name".equals(section.getName))
.findFirst();
但是如何在单行中使用optional执行相同操作呢。我的正文或节可能为空
我试过下面的方法,但不起作用
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();
我无法在一条生产线上完成这项工作。我试着做平面图,但效果不好。请告知我们是否可以在一条生产线上实现这一点
下面是完整的模式供参考
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;
}
}
类请求{
身体;
公共机构{
返回体;
}
公共机构(机构){
这个身体=身体;
}
}
阶级团体{
列出各节;
公共列表getSections(){
回流段;
}
公共无效设置部分(列出部分){
本节=节;
}
}
班级{
私有字符串名称;
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
}
您需要将表示单个值的可选
转换为流
,以完成过滤器
和findFirst()
操作。至少有一种方法是映射到空的流
(或空的列表
,如相邻答案所示),以防出现任何空值:
Optional.ofNullable(request)
.map(Request::getBody)
.map(Body::getSections)
.map(List::stream)
.orElse(Stream.empty())
.filter(section -> "name".equals(section.getName))
.findFirst();
这应该适合您:
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()使用.flatMap(sections->sections.stream().filter(section->“name”.equals(section.getName())).findFirst())编码>代码>现在我明白了。非常感谢你。