Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value of Optional to a variable if present

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?

like image 726
chrisrhyno2003 Avatar asked Sep 26 '16 21:09

chrisrhyno2003


People also ask

How do you find the Optional value of a present?

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.

How do you declare an Optional variable in Java?

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.

Can you set Optional to null?

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).

What is Optional <> in Java?

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.


2 Answers

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();
like image 119
CompilaMente Avatar answered Sep 18 '22 12:09

CompilaMente


Quite late but I did following:

String myValue = object.map(x->x.getValue()).orElse("");
                           //or null. Whatever you want to return.
like image 30
Optional Avatar answered Sep 19 '22 12:09

Optional