Arthur Arthur - 6 months ago 20
Java Question

Optional for definitely null values in Java 8

What is a sense of this?

Optional.of(someLinkToNull).ifPresent(present -> {

gives NullpointerException.

Please, give an example, how to check on null with Optional (less code)?


Use ofNullable static factory method rather than of - the latter does not allow the value to be null:

Optional.ofNullable(someLinkToNull).ifPresent(present -> {

Note that while it's fine to write code like that when learning about optional, the usual use case for it is to pass an object which itself might be null, through a chain of transformations which also could reduce it to null, and not branch out like crazy to avoid NPEs. In your case a simple null-check if should be sufficient (as 4castle mentioned in the comments). Consider for example this meaningless piece of code:

            .flatMap(charges ->

Several things might go wrong here:

  • order might be null
  • there could be no fee associated with the order
  • the fee issuer might not have address (it might not be known if the order is from a third-party system)
  • the issuer's address might not specify a street (for example boats don't have any street associated with them)

As you can see there are at least four null checks there already, instead of a nice Optional fluent thingie like the one above.You can also check out documentation for null-safe chaining