I'm using guava 20.0 and java 7. I have guava function
public static Function<String, Optional<String>> UP
= new Function<String, Optional<String>>() {
@Override
public Optional<String> apply(String f) {
if (f.equals("test"))
return Optional.absent();
return Optional.of(f.toLowerCase());
}
};
This code:
Optional<String> strNormal = Optional.of("test");
Optional<String> str = Optional.absent();
System.out.println("strNormal = " + strNormal.transform(UP));
System.out.println("str = " + str.transform(UP));
prints:
strNormal = Optional.of(Optional.absent())
str = Optional.absent()
But how can I receive Optional.absent() in both cases. May be there is something like map function for Optional.
Someone already suggested to add this "map" function in Guava 's Optional
.However , it is rejected as Optional
is considered as legacy and will be frozen.
Your best bet is to write an utility function , something like :
public static Optional<F> transform(Optional<T> optional, Function<T, F> transformer) {
try {
return optional.transform(transformer);
catch (NullPointerException e) {
return Optional.<F>.absent()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.