You could use a filter:
Optional.ofNullable(s).filter(not(String::isEmpty));
That will return an empty Optional if ppo is null or empty.
Videos
Creating an Optional out of the return value of a method seems a bit awkward. Rather let your getObjectOrNullIfNotAvailable() method return an Optional in the first place. Then use the map operator to convert it in to a string. Here's how it looks.
Optional<Object> oa = someOptionalReturningMethod();
String value = oa.map(Object::toString).orElse(null);
For some reason if you can't change the return value of the method to an Optional, just leave the imperative solution using the ternary operator. Nothing wrong with that.
String value = a==null ? null : a.toString();
Use:
String value = Optional.ofNullable(getObjectOrNullIfNotAvailable()).map(Object::toString).orElse(null);
Otherwise, you can check if an Object is null and return in that case a String with "null" inside with String.valueOf(Object obj) or Objects.toString(Object obj). Eg.
String value = Objects.toString(getObjectOrNullIfNotAvailable())
In my program, it asks for your name by using a TextInputDialog, but it only works with Optional Strings, but I need a way to convert Optional <String> to String.
My Code.
TextInputDialog dialogP1 = new TextInputDialog();
dialogP1.setTitle("Player 1");
dialogP1.setHeaderText("Player 1's Name");
dialogP1.setContentText("Your Name");
player1NameOptional = dialogP1.showAndWait();I have tried this but that did not work.
player1Name = (player1NameOptional.get());
Is there a way to convert Optional <String> to String? How?