java - 在方法中使用泛型谓词和函数
问题描述
我对这里的仿制药相当陌生,需要一些帮助。
我正在尝试使用 Generic Predicate
、 Generic java.util Function
、 GenericList
作为参数创建一个 Generic 方法。方法是这样的:
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;
}
推荐阅读
- node.js - Alpine 构建中的 Parceljs 抛出:找不到模块 './artifacts/index.linux-arm64-musl.node'
- spring - 有任何在线编辑器或IDE支持spring boot吗?
- node.js - 下载没有文件结尾nodejs的文件
- python - 绘图前修改matplotlib生成的直方图
- android - 我没有找到任何电子邮件/密码选项(firebase-auth)
- javascript - 我的 Google Apps 脚本基于时间的触发器拒绝工作,即使它没有显示任何错误
- linkedin - LinkedIn alt-text 的最大长度?
- flutter - setState 在 futureBuilder 上的 ontap 异步中不起作用
- c - 有没有办法在结构中自动创建结构
- python - 如何在 unittest 下运行的 doctest 中抑制 ResourceWarning()s