I have a method that procudes an Optional
But this String must be parsed at another application level as Integer or Long.
This I h
I guess you can do:
public static void main(final String[] args) {
final Optional valid = Optional.of("42")
.transform(STR_TO_INT_FUNCTION)
.or(Optional.absent());
System.out.println(valid); // Optional.of(42)
final Optional invalid = Optional.of("Toto")
.transform(STR_TO_INT_FUNCTION)
.or(Optional.absent());
System.out.println(invalid); // Optional.absent()
final Optional absent = Optional.absent()
.transform(STR_TO_INT_FUNCTION)
.or(Optional.absent());
System.out.println(absent); // Optional.absent()
}
private static final Function> STR_TO_INT_FUNCTION =
new Function>() {
@Override
public Optional apply(final String input) {
return Optional.fromNullable(Ints.tryParse(input));
}
};
Usage isn't that clumsy when you use Optional -> transform -> or in one line (assigning transformed optional integer would produce Optional
).