我在这里对泛型还不陌生,希望获得一些帮助。
我正在尝试使用泛型Predicate
,泛型java.util Function
,泛型List
作为参数来创建泛型方法。方法是这样的:
public static <T> T getValue(Predicate<? super Object> condition, Function<? super Object, ? extends Object> mapper, T elseResult, List<T> table) {
T result = null;
if (table != null)
result = table.stream()
.filter(condition)
.map(mapper).findAny().orElse(elseResult); // Syntax error here.
else
result = elseResult;
return (T) result;
}
我在orElse(elseResult)
方法上遇到错误。这是错误-
The method orElse(capture#1-of ? extends Object) in the type Optional<capture#1-of ? extends Object> is not applicable for the arguments (T).
我不确定这个错误是什么。那么有人可以告诉我我在做什么错吗?谢谢。
您的mapper
可以返回任何内容,因此您的orElse
方法不一定会返回T
。
如果将mapper
更改为Function<T,T> mapper
,您的代码将通过编译。
如果希望映射器能够返回其他类型,请添加第二个类型参数:
public static <T,S> S getValue(Predicate<? super Object> condition, Function<T,S> mapper, S elseResult, List<T> table) {
S result = null;
if (table != null)
result = table.stream()
.filter(condition)
.map(mapper).findAny().orElse(elseResult);
else
result = elseResult;
return result;
}