Java Optional Get if Present

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.

+6
source share
1 answer

You can call gen.writeObject as the user of your object in ifPresent :

 value.ifPresent(gen::writeObject); 

This will call the method only if Optional not empty.

In your example, the writeObject method writeObject IOException thrown; you will need to catch it and instead throw an exception from the runtime instead (for example, a new UncheckedIOException , which complicates the code a bit) or do something else (for example, log it):

 value.ifPresent(v -> { try { gen.writeObject(v); } catch (IOException e) { throw new UncheckedIOException(e); } }); 
+14
source

All Articles