I'm learning about Optional class. I'm just a bit confused about the correct use of the method Optional.ifPresent(Consumer<? super T> consumer)
.
I see this example on one project:
Optional.ofNullable(user.getIdentifiantAAA())
.ifPresent(id -> identifiants.add(new Identifiant(id, IdentifiantType.AAA));
IMHO, this is less readable than:
if (user.getIdentifiantAAA() != null) {
identifiants.add(user.getIdentifiantAAA());
}
A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
I feel that the use of Optional.ifPresent of the example breaks the principal propose of this class. An instance of Optional is created only to use the isPresent method, is it really necessary for this case?
So, my question is: should be wrap objects in Optional to ckeck non null and execute code with the method Optional.ifPresent(Consumer<? super T> consumer)
?