I have a java optional object that I only want to get if it's present. The obvious code here is:
JsonGenerator gen;
if(value.isPresent()) {
gen.writeObject(value.get());
}
But I want to see if I can steamline that to 1 line with the ifPresent
method. I don't want it to write at all if it's not present. I tried something like this:
gen.writeObject(value.ifPresent(a -> a));
But that clearly didn't work. Is there any way to do what I want? Everything I've researched online only shows the use of ifPresent
with a method call for the predicate.
Edit 1: I tried Tunaki's solution but I am getting the following error:
Error:(25, 46) java: incompatible thrown types java.io.IOException in method reference
Here's my entire block of code:
public class FooSerializer extends JsonSerializer<Foo> {
@Override
public void serialize(Foo value,
JsonGenerator gen,
SerializerProvider serializers) throws IOException {
value.getFooA().ifPresent(gen::writeObject);
}
}
I even tried:
public class FooSerializer extends JsonSerializer<Foo> {
@Override
public void serialize(Foo value,
JsonGenerator gen,
SerializerProvider serializers) throws IOException {
try {
value.getContactInfo().ifPresent(gen::writeObject);
} catch(IOException e) {
throw new UncheckedIOException(e);
}
}
}
But it still gives me the error.
The ifPresentOrElse method of the Optional class is an instance method that is used to perform an action based on whether or not the object's value is present. This method implements the Consumer interface and an implementation of the Runnable interface.
It returns an Optional containing the value if is not empty and satisfy the specified predicate, an empty Optional otherwise.
The ifPresent method of the Optional class is an instance method that performs an action if the class instance contains a value. This method takes in the Consumer interface's implementation whose accept method will be called with the value of the optional instance as the parameter to the accept method.
You can invoke gen.writeObject
as a consumer of your object in ifPresent
:
value.ifPresent(gen::writeObject);
This will invoke the method only if the Optional
isn't empty.
In your example, the method writeObject
throws the checked exception IOException
; you will need to catch it and either throw a runtime exception instead (like the new UncheckedIOException
, which complicates a little the code) or do something else (like log it):
value.ifPresent(v -> {
try {
gen.writeObject(v);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With