I have an Optional-routine to check if I have a null-reference:
ToDo todo = new ToDo("Foo");
Optional<ToDo> candidateString = Optional.ofNullable(todo);
// Get the length of the String or 9 as a default value.
int lengthS = candidateString.map(c -> c.getId().length()).orElse(9);
System.out.println("Length of String: " + lengthS);
The ToDo-class is a simple class essentially being a container for a String, so I can force a null-reference within it:
public class ToDo {
private String id;
public ToDo() {
}
public ToDo(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
If I insert "Foo" as a String to the constructor, every thing works fine. If I leave it empty, I would expect the default value defined by orElse(9) to be returned. Instead I get a NullPointerException which makes the hole Optional-code pointless.
How do I make the code return the default value 9, if I leave the constuctor empty? That is, if I change the first line to:
ToDo todo = new ToDo();
Thank you for your feedback in advance
Threx