How to Add Optional to List Only If Present and Exists in Java
How do we add an Optional value to a list only if it is present?
Suppose we have an Optional opt
that we want to add to this list lst
only if a value exists.
ArrayList<String> lst = new ArrayList<>();
Optional<String> opt = getOptionalFromSomewhere();
Add to list using isPresent()
We can use the isPresent()
function on the Optional
instance to check if a value is present.
if (opt.isPresent()) {
lst.add(opt.get())
}
Add to list using ifPresent()
We can be slightly more concise by using ifPresent()
, which will perform some action if a value is present.
opt.ifPresent(lst::add);
We can modify this to run some callback function if a value exists.
opt.ifPresent(value -> {
// do something with value
});
Note that the callback should not return anything itself. Any return value will be lost.