I came across the below code:
public void method(MyObject obj) {
String value = Optional.ofNullable(obj)
.map(x -> obj.doSomething())
.orElse(MyObject.DEFAULT_VALUE);
}
I am curious to know the usage of x -> obj.doSomething() instead of x -> x.doSomething() in map method.
Here even if obj is null, a NullPointerException would NOT be thrown because we are invoking the ofNullable method before the map and hence the mapping function would be invoked only when obj is not null.
So in terms of the results, both x -> obj.doSomething() or x -> x.doSomething() would be equivalent in the case of Optional. (Obviously the result would be different in case of a Stream or when using Optional.of).
Are there any other differences? And in terms of usage, I think x -> x.doSomething() should be preferred rather than using the actual object itself.
objisnull, thenobj.doSomething()will throw a NPE. We should usex -> x.doSomething()or, even better, use a method reference:...map(MyObject::doSomething)....objis slightly larger than usingxx -> x.doSomething()makes more sense.