【发布时间】:2021-10-16 22:05:06
【问题描述】:
我有一个具体的类 MyObjectWrapper 和一个接口 MyObject。
MyObjectWrapper implements MyObject
MyObjectWrapper.jsonObject 包含 MyObjectJson 的一个实例。
MyObjectWrapper 的构造函数签名是:
MyObjectWrapper(MyObjectJson myObjectJson, ServiceManager serviceManager)
我想为方法提供一个 PaginatedList 实例,并包含对上述 MyObjectWrapper 构造函数的引用,以便可以为 PaginatedList 中的每个项目引用它,这样我的 stream() 的结果是一个新的 PaginatedList 实例,其中 MyObjectWrapper是具体的 MyObject。
无论在哪里调用 mapList,我都会引用 this.getServiceManager()。我假设我必须将 MyObjectWrapper 的构造函数作为函数传递,但不确定如何编写方法签名,也不确定如何正确引用构造函数作为方法本身中的映射函数。
我的代码如下所示,但我想让该方法通用,因此我不必为每种类型都复制它。
PaginatedList<T> extends ArrayList<T>
private PaginatedList<MyObject> mapList(PaginatedList<MyObjectJson> paginatedList) {
return paginatedList.stream()
.map(jsonObject -> new MyObjectWrapper(jsonObject, this.getServiceManager()))
.collect(Collectors.toCollection(PaginatedList::new));
}
【问题讨论】:
-
您的代码中已经有一个示例:
MyObjectWrapper::new。如果您只需要预先配置某些参数,您可以说moj -> new MyObjectWrapper(moj, serviceManagerVariable)。
标签: java generics collections java-stream