有效地使用Java Optional.ofNullable

dru*_*123 2 java optional java-8

我可以使用Java8提取特定部分,如下所示

request.getBody()
       .getSections()
       .filter(section -> "name".equals(section.getName))
       .findFirst();
Run Code Online (Sandbox Code Playgroud)

但是如何在一行中使用可选项来做同样的事情.我的身体或部分可能为空.

我尝试了以下但没有工作

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();
Run Code Online (Sandbox Code Playgroud)

我无法让这个工作在一条线上.我试过做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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Kay*_*man 6

您需要将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();
Run Code Online (Sandbox Code Playgroud)