问题描述
我有一种禁止Optional<String>
但是此String必须在另一个应用程序级别解析为Integer或Long.
But this String must be parsed at another application level as Integer or Long.
我有一个Function<String, Integer>
,可以在String上应用它,以产生一个Integer.这种转换可能会失败,因为String可能不是整数可解析的值.
This I have a Function<String, Integer>
that can be applied on the String, to produce an Integer.This transformation can fail because the String may not be an Integer parsable value.
当转换失败时,我想返回Optional,而不是抛出解析异常.
I would like to return Optional when the transformation fails, instead of throwing a parsing exception.
我不能使STRING_TO_INTEGER_FUNCTION返回null,因为番石榴不允许这样做:
I can't make the STRING_TO_INTEGER_FUNCTION return null, because it is not allowed by Guava:
Exception in thread "main" java.lang.NullPointerException: Transformation function cannot return null.
因此,我唯一能做的就是拥有一个Function<String,Optional<Integer>>
,但最终得到的结果却是一个Optional<Optional<Integer>>
,它并不是很酷,因为我可能需要对其进行其他转换.
Thus the only thing I can do is having a Function<String,Optional<Integer>>
but then I get as final result an Optional<Optional<Integer>>
which isn't really cool because I may have another transformations to apply on it.
有人知道我该如何在番石榴中做类似的事情吗?
Does someone know how can I do something like that in Guava?
Optional.of("Toto").transform(STRING_TO_INTEGER_FUNCTION) = // Optional<Integer> ?
谢谢
推荐答案
我想您可以做到:
public static void main(final String[] args) {
final Optional<Integer> valid = Optional.of("42")
.transform(STR_TO_INT_FUNCTION)
.or(Optional.<Integer>absent());
System.out.println(valid); // Optional.of(42)
final Optional<Integer> invalid = Optional.of("Toto")
.transform(STR_TO_INT_FUNCTION)
.or(Optional.<Integer>absent());
System.out.println(invalid); // Optional.absent()
final Optional<Integer> absent = Optional.<String>absent()
.transform(STR_TO_INT_FUNCTION)
.or(Optional.<Integer>absent());
System.out.println(absent); // Optional.absent()
}
private static final Function<String, Optional<Integer>> STR_TO_INT_FUNCTION =
new Function<String, Optional<Integer>>() {
@Override
public Optional<Integer> apply(final String input) {
return Optional.fromNullable(Ints.tryParse(input));
}
};
当您使用Optional-> transform->或一行时,
用法不是 笨拙(分配转换后的可选整数会产生Optional<Optional<Integer>>
).
Usage isn't that clumsy when you use Optional -> transform -> or in one line (assigning transformed optional integer would produce Optional<Optional<Integer>>
).
这篇关于Guava可选类型,当转换返回另一个Optional时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!