有效使用Java Optional.ofNullable

3
我可以像下面这样使用Java8提取特定部分:

我可以使用Java8提取特定部分,例如以下代码:

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;
    }

}

1
.filter(section -> "name".equals(section.getName)).findFirst(); 替换为 .flatMap(sections -> sections.stream() .filter(section -> "name".equals(section.getName())).findFirst()); - Holger
2个回答

6

您需要将表示单个值的Optional转换为Stream,以完成filterfindFirst()操作。至少有一种方法是在出现任何空值的情况下映射到一个空的Stream(或者像相邻答案中那样映射为空的List):

Optional.ofNullable(request)
    .map(Request::getBody)
    .map(Body::getSections)
    .map(List::stream)
    .orElse(Stream.empty())
    .filter(section -> "name".equals(section.getName))
    .findFirst();

现在我明白了。非常感谢你。 - druid1123

3
这对你来说应该可行:

这应该对您有帮助:

Optional.ofNullable(request)
    .map(Request::getBody)
    .map(Body::getSections)
    .orElse(Collections.emptyList())
    .stream()
    .filter(section -> "name".equals(section.getName))
    .findFirst();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接