有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

与简单的空检查相比,使用(平面)映射的java优势是什么?

我正在阅读下面的资料,我想知道为什么我会用平面地图的方式。在我看来,实例化的对象要多得多,执行的代码比通过if语句执行的简单null检查要多,它将在第一个null处终止,而不必检查其他对象,并且非常适合包装器

在我看来,if检查更快,内存更安全(速度对我来说非常关键,因为我通常只有2-3毫秒的时间来执行很多代码,如果有的话)

使用“(平面)地图”可选方式的优点是什么?为什么我应该考虑切换到它?

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

class Outer {
    Nested nested;
}

class Nested {
    Inner inner;
}

class Inner {
    String foo;
}

In order to resolve the inner string foo of an outer instance you have to add multiple null checks to prevent possible NullPointerExceptions:

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

The same behavior can be obtained by utilizing optionals flatMap operation:

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

共 (1) 个答案

  1. # 1 楼答案

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

    假设我们正在处理一个名为itemsArrayListOutersOuters字符串,如果存在,则需要获取一个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);
    

    但是我不得不重复我自己,关于如何从外部(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());
    

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

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

    替代方案可能如下所示:

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