I have an optional java object that I want to get only if it is present. The obvious code is here:
JsonGenerator gen; if(value.isPresent()) { gen.writeObject(value.get()); }
But I want to see if I can include this line in 1 line using the ifPresent method. I do not want him to write at all if he is not present. I tried something like this:
gen.writeObject(value.ifPresent(a -> a));
But that clearly didn't work. Is there a way to do what I want? Everything I explored on the Internet only shows the use of ifPresent with a method call for the predicate.
Edit 1: I tried Tunaki's solution, but I get the following error:
Error:(25, 46) java: incompatible thrown types java.io.IOException in method reference
Here is my whole 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 that still gives me an error.
source share