【问题标题】:How to use Optional in Java8如何在 Java8 中使用 Optional
【发布时间】:2018-02-13 08:18:31
【问题描述】:

对 Optional 的用法有点困惑。 如何使用 Optional 获得相同的结果?

ModuleEntity module = n.getOutline().getModule()==null?n.getOutline().getParent().getModule():n.getOutline().getModule();
return m.getModule().equals(module)

尝试了很多,但总是NullpointerException...

例如

m.getModule().equals(Optional.ofNullable(n.getOutline().getModule()).orElse(n.getOutline().getParent().getModule())))

完整代码如下:

List<RoleModel> roles = app.getRoles().stream()
            .filter(r -> RoleType.MODULE.equals(r.getType()))
            .collect(Collectors.toList()).stream()
            .map(m -> {
                        RoleModel role = Entity2ModelUtils.entity2Model(m);
                        role.setRoles(app.getRoles().stream()
                                    .filter(o -> RoleType.OUTLINE.equals(o.getType()))
                                    .collect(Collectors.toList()).stream()
                                        .filter(n -> m.getModule().equals(Optional.ofNullable(n.getOutline().getModule()).map(zz->n.getOutline().getModule()).orElse(n.getOutline().getParent().getModule())))
                                        .map(z -> Entity2ModelUtils.entity2Model(z))
                                        .collect(Collectors.toList()));
                        return role;})
            .collect(Collectors.toList());

【问题讨论】:

  • 什么是 n ?显示该课程
  • 另一个对象..添加了完整代码
  • 最好能说出你想要达到的目标。
  • @pvpkiran reuturn a==null?b:c 这就是我想要做的。
  • 使用Optional来替换三元语句是一种可疑的做法,但a==null ? b : a可以写成Optional.ofNullable(a).orElse(b)

标签: java-8 optional


【解决方案1】:

正如 cmets 中所说,不要使用 Optional 来替换三元语句。请参阅问题Uses for Optional 了解更多信息。

但如果你真的想在你的情况下使用Optional,你可以这样做:

Optional
  .ofNullable(n.getOutline().getModule())
  .orElseGet(() -> n.getOutline().getParent().getModule());

这里的关键是 else 语句的惰性求值。我猜当您使用Optional.ofNullable(...).orElse(...) 时,总是执行的orElse 的内容会引发空指针异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2022-06-10
    相关资源
    最近更新 更多