1

A little confused about the usage of Optional. How to get the same result with Optional?

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

tried a lot, but always NullpointerException...

eg:

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

Here is the complete code:

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());
Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86
StupidPz
  • 403
  • 1
  • 4
  • 14

1 Answers1

3

As said in the comments, do not use Optional just to replace a ternary statement. See question Uses for Optional for more information.

Though if you really want to use an Optional in your case, you could do:

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

The key here is the lazy evaluation of the else statement. I guess when you were using Optional.ofNullable(...).orElse(...), it was the content of the orElse that were always executed that throw the nullpointer exception.

amanteaux
  • 2,063
  • 21
  • 24