Today I came across a very elegant use (IMHO) of Optional
at work.
Consider the same person as above with a date of birth attribute:
public class Person {
private String name;
private String dob;
// getters & setters etc etc (yep Java is verbose !!!!)
}
Now say you want to get that dob
value into a Date
object and do weird and wonderful date calculations.
You could use Optional
like this:
// if you expect dob to be a string in the format yyyy-mm-dd
LocalDate birthday = Optional.ofNullable(persone.getDob())
.map(LocalDate::parse)
.orElse(null); // or whatever
// or if the dob is in a different format, for example dd-MM-yyyy
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = Optional.ofNullable(p.getDob())
.map(dob -> LocalDate.parse(dob, formatter))
.orElse(null);
Now you have a LocalDate
instance to play with.
In fact, once you have an Optional
instance you have the following stream operators available
map
flatMap
filter
flatMap
can be used to compose Optional
s
public int ageDifference(Optional<Person> older, Optional<Person> younger) {
return older.flatMap(o -> younger.map(y -> calAgeDifference(o.getDob(), y.getDob()));
}
Quite cool
Just thought I’d share