java - 有效使用 JavaOptional.ofNullable

标签 java java-8 option-type

我可以使用 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;
    }

}

最佳答案

您需要从表示单个值的 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();

关于java - 有效使用 JavaOptional.ofNullable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46681866/

相关文章:

Java, window : Get process name of given PID

eclipse - 为什么相同的代码在 Eclipse 中有效,但在 IntelliJ 中甚至无法编译

java - Bazel:FlywayDB java.lang.UnsupportedClassVersionError

json - 忽略不支持的解码器

swift - 在 Swift 中默认类型推断变量是 "optionals"吗?

java - 根据字符串是否为空创建Guava的Optional的简洁方法

java - Maven构建多模块项目成功,Eclipse报错

Java : Impossible to parse "23/10/1973" with "dd/MM/yyyy HH:mm" format

java - 限制final变量赋值的原因

java - 如何在 Java 8 中将 Map<Shape, int[]> 转换为 Map<Shape, Set<Integer>>?