小编dru*_*123的帖子

有效地使用Java Optional.ofNullable

我可以使用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 …
Run Code Online (Sandbox Code Playgroud)

java optional java-8

2
推荐指数
1
解决办法
1322
查看次数

标签 统计

java ×1

java-8 ×1

optional ×1