Hi I am using Java Optional. I saw that the Optional has a method ifPresent.
Instead of doing something like:
Optional<MyObject> object = someMethod();
if(object.isPresent()) {
String myObjectValue = object.get().getValue();
}
I wanted to know how I can use the Optional.ifPresent() to assign the value to a variable.
I was trying something like:
String myValue = object.ifPresent(getValue());
What do I need the lambda function to be to get the value assigned to that variable?
Retrieving the value using get() method Optional's get() method returns a value if it is present, otherwise it throws NoSuchElementException. You should avoid using get() method on your Optionals without first checking whether a value is present or not, because it throws an exception if the value is absent.
If you want a variable to be optional, you can overload the method using a signature which doesn't require the parameter. Method overloading is a good answer in my opinion, while varargs is a very bad answer.
You can use optional when you want a variable or constant contain no value in it. An optional type may contain a value or absent a value (a null value).
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.
You could use #orElse or orElseThrow to improve the readbility of your code.
Optional<MyObject> object = someMethod();
String myValue = object.orElse(new MyObject()).getValue();
Optional<MyObject> object = someMethod();
String myValue = object.orElseThrow(RuntimeException::new).getValue();
Quite late but I did following:
String myValue = object.map(x->x.getValue()).orElse("");
//or null. Whatever you want to return.
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