You could use orElse(null):
String o = getOptional().orElse(null);
if (o == null) {
return;
}
Answer from dnault on Stack OverflowVideos
You could use orElse(null):
String o = getOptional().orElse(null);
if (o == null) {
return;
}
You can use ifPresent and map methods instead, if the function is void and you need to do side-effects you can use ifPresent,
optional.ifPresent(System.out::println);
If another method return relies on the Optional than that method might need to return an Optional as well and use the map method
Optional<Integer> getLength(){
Optional<String> hi = Optional.of("hi");
return hi.map(String::length)
}
Most of the time when you call isPresent and get, you are misusing Optional.
Since the whole purpose of Optional is to represent values that might not exist, why does the constructor of Optional require a non-null value? Is it becuase they wanted to coalesce all empty Optionals down to a single instance? Even if that's true, why not make Optional.of() behave the way Optional.ofNullable() and do away with the ofNullable() method?
Edit to clarify my opinion and respond to some of the points raised:
My opinion stated clearly, is only two "constructor" methods should exist:
of (and it should work like the current ofNullable method)
empty
So far the arguments against my opinion have been:
Having .of() and .ofNullable() makes it clear at the point of construction when the value exists and when it might not exist.
This is true, but that clarity is redundant. For safety, the call to .of() will either be inside the not-null branch of a null-check, or come after a not-null assertion. So even if .of() behaved as .ofNullable() does it would be clear that the value exists.
2. It guards against changes in behavior of the the methods supplying the values. If one of the supplying methods suddenly changes from never returning nulls to sometime returning nulls it will catch the error.
I would argue that guarding against this occurrence is the responsibility of the function returning the Optional values, and not the responsibility of Optional. If the function needs to guard against a null value so that it can handle it in some fashion (eg. by calling another supplier method) then then it needs to implement the not-null assertion explicitly in the body of its code. This is more clear than relying on an class called Optional do something that is semantically at odds with the plain reading of its class name.
In the case where the function doesn't care whether the value returned from the supplier is null or not, it should simply be able to call .of() to create the optional and return it.
With Java 9 or higher, ifPresentOrElse is most likely what you want:
Optional<> opt = dao.find();
opt.ifPresentOrElse(obj -> obj.setAvailable(true),
() -> logger.error("…"));
Currying using vavr or alike might get even neater code, but I haven't tried yet.
I don't think you can do it in a single statement. Better do:
if (!obj.isPresent()) {
logger.fatal(...);
} else {
obj.get().setAvailable(true);
}
return obj;
If you are using Java 9+, you can use ifPresentOrElse() method:
opt.ifPresentOrElse(
value -> System.out.println("Found: " + value),
() -> System.out.println("Not found")
);
For me the answer of @Dane White is OK, first I did not like using Runnable but I could not find any alternatives.
Here another implementation I preferred more:
public class OptionalConsumer<T> {
private Optional<T> optional;
private OptionalConsumer(Optional<T> optional) {
this.optional = optional;
}
public static <T> OptionalConsumer<T> of(Optional<T> optional) {
return new OptionalConsumer<>(optional);
}
public OptionalConsumer<T> ifPresent(Consumer<T> c) {
optional.ifPresent(c);
return this;
}
public OptionalConsumer<T> ifNotPresent(Runnable r) {
if (!optional.isPresent()) {
r.run();
}
return this;
}
}
Then:
Optional<Any> o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s -> System.out.println("isPresent " + s))
.ifNotPresent(() -> System.out.println("! isPresent"));
Update 1:
the above solution for the traditional way of development when you have the value and want to process it but what if I want to define the functionality and the execution will be then, check below enhancement;
public class OptionalConsumer<T> implements Consumer<Optional<T>> {
private final Consumer<T> c;
private final Runnable r;
public OptionalConsumer(Consumer<T> c, Runnable r) {
super();
this.c = c;
this.r = r;
}
public static <T> OptionalConsumer<T> of(Consumer<T> c, Runnable r) {
return new OptionalConsumer(c, r);
}
@Override
public void accept(Optional<T> t) {
if (t.isPresent()) {
c.accept(t.get());
}
else {
r.run();
}
}
Then could be used as:
Consumer<Optional<Integer>> c = OptionalConsumer.of(
System.out::println,
() -> System.out.println("Not fit")
);
IntStream.range(0, 100)
.boxed()
.map(i -> Optional.of(i)
.filter(j -> j % 2 == 0))
.forEach(c);
In this new code you have 3 things:
- can define the functionality before the existing of an object easy.
- not creating object reference for each Optional, only one, you have so less memory than less GC.
- it is implementing consumer for better usage with other components.
By the way, now its name is more descriptive it is actually Consumer<Optional<?>>
Optional harnesses the type system for doing work that you'd otherwise have to do all in your head: remembering whether or not a given reference may be null. This is good. It's always smart to let the compiler handle boring drugework, and reserve human thought for creative, interesting work.
Without Optional, every reference in your code is like an unexploded bomb. Accessing it may do something useful, or else it may terminate your program wth an exception.
With Optional and without null, every access to a normal reference succeeds, and every reference to an Optional succeeds unless it's unset and you failed to check for that. That is a huge win in maintainability.
Unfortunately, most languages that now offer Optional haven't abolished null, so you can only profit from the concept by instituting a strict policy of "absolutely no null, ever". Therefore, Optional in e.g. Java is not as compelling as it should ideally be.
An Optional brings stronger typing into operations that may fail, as the other answers have covered, but that is far from the most interesting or valuable thing Optionals bring to the table. Much more useful is the ability to delay or avoid checking for failure, and to easily compose many operations that may fail.
Consider if you had your optional variable from your example code, then you had to perform two additional steps that each might potentially fail. If any step along the way fails, you want to return a default value instead. Using Optionals correctly, you end up with something like this:
return optional.flatMap(x -> x.anotherOptionalStep())
.flatMap(x -> x.yetAnotherOptionalStep())
.orElse(defaultValue);
With null I would have had to check three times for null before proceeding, which adds a lot of complexity and maintenance headaches to the code. Optionals have that check built in to the flatMap and orElse functions.
Note I didn't call isPresent once, which you should think of as a code smell when using Optionals. That doesn't necessarily mean you should never use isPresent, just that you should heavily scrutinize any code that does, to see if there is a better way. Otherwise, you're right, you're only getting a marginal type safety benefit over using null.
Also note that I'm not as worried about encapsulating this all into one function, in order to protect other parts of my code from null pointers from intermediate results. If it makes more sense to have my .orElse(defaultValue) in another function for example, I have much fewer qualms about putting it there, and it's much easier to compose the operations between different functions as needed.
An Optional always contains a non-null value or is empty, yes, but you don't have an Optional, you have a reference of type Optional pointing to null. You need to initialize testString, e.g. to Optional.empty().
Optional isn't magic, it's an object like any other, and the Optional reference itself can be null. It's the contents of the Optional that can't be null.
From the oracle documentation for the Optional type :
A container object which may or may not contain a non-null value.
So, yes it will return null if the variable is set to null. More info here