使用(平面)映射比简单的空检查有什么优势?

Tsc*_*cka 3 java

我正在阅读下面的源代码,我想知道为什么我要使用平面图方式。正如我所看到的,与通过 if 语句进行简单的 null 检查相比,实例化了更多的对象,执行了更多的代码,后者将在第一个 null 处终止,而不必费心检查其他内容,并且非常适合包装器。

正如我所见,if 检查更快+内存更安全(速度对我来说非常重要,因为我通常只有 2-3 毫秒来执行大量代码(如果有的话)

使用“(flat)Map”可选方式有什么好处?我为什么要考虑改用它?

来自http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

class Outer {
    Nested nested;
}

class Nested {
    Inner inner;
}

class Inner {
    String foo;
}
Run Code Online (Sandbox Code Playgroud)

为了解析外部实例的内部字符串 foo,您必须添加多个 null 检查以防止可能的 NullPointerExceptions:

Outer outer = new Outer();
if (outer != null && outer.nested != null && outer.nested.inner != null) {
    System.out.println(outer.nested.inner.foo);
}
Run Code Online (Sandbox Code Playgroud)

通过使用可选的 flatMap 操作可以获得相同的行为:

Optional.of(new Outer())
    .flatMap(o -> Optional.ofNullable(o.nested))
    .flatMap(n -> Optional.ofNullable(n.inner))
    .flatMap(i -> Optional.ofNullable(i.foo))
    .ifPresent(System.out::println);
Run Code Online (Sandbox Code Playgroud)

wes*_*ton 6

我认为Optional在更广泛的流媒体环境中使用 会更清晰,而不是单行。

假设我们正在处理一个ArrayListofOuters调用items,并且要求是获取字符串流foo(如果存在)。

我们可以这样做:

//bad example, read on
Stream<String> allFoos = list.stream()
            .filter(o -> o != null && o.nested != null && o.nested.inner != null)
            .map(o -> o.nested.inner.foo);
Run Code Online (Sandbox Code Playgroud)

但我不得不重复一遍,关于如何从外部 (o != null && o.nested != null && o.nested.inner != nullo.nested.inner.foo)获取字符串

Stream<String> allFoos =
        list.stream()
                .map(o -> Optional.ofNullable(o)
                        .map(t -> t.nested)
                        .map(n -> n.inner)
                        .map(i -> i.foo))
                .filter(s -> s.isPresent())
                .map(s -> s.get());
Run Code Online (Sandbox Code Playgroud)

这也为我提供了一种插入默认值的简单方法:

Stream<String> allFoos =
            list.stream()
                    .map(o -> Optional.ofNullable(o)
                            .map(t -> t.nested)
                            .map(n -> n.inner)
                            .map(i -> i.foo)
                            .orElse("Missing"));
Run Code Online (Sandbox Code Playgroud)

另一种选择可能如下所示:

//bad example (IMO)
Stream<String> allFoos = list.stream()
            .map(o -> o != null && o.nested != null && o.nested.inner != null ?
                    o.nested.inner.foo : "Missing");
Run Code Online (Sandbox Code Playgroud)