this post was submitted on 16 Jun 2023
16 points (100.0% liked)

Java

1416 readers
1 users here now

For discussing Java, the JVM, languages that run on the JVM, and other related technologies.

founded 2 years ago
MODERATORS
 

I'm curious if there are things in the standard class library that you find useful but not widely used.

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 1 points 2 years ago (1 children)

Instead of wrapping it in an optional you can do Objects.requireNonNullElse(value, defaultValue)

[โ€“] austin 1 points 1 year ago* (last edited 1 year ago)

Optional has more syntactic sugar for more complex scenarios / functional call chaining that prevents repetitive if checks

Optional.ofNullable(myObj)
  .map(MyClass::getProperty)
  .map(MyOtherClass::getAnotherProperty)
  .filter(obj -> somePredicate(obj))
  .orElse(null)

This is completely null safe, the function calls are only made if the object is not null