【问题标题】:How do I pass a Constructor as a Function to a generic method and then use that Constructor in a stream().map() operation?如何将构造函数作为函数传递给泛型方法,然后在 stream().map() 操作中使用该构造函数?
【发布时间】: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 -&gt; new MyObjectWrapper(moj, serviceManagerVariable)。

标签: java generics collections java-stream


【解决方案1】:

由于构造函数将MyObjectJson 和ServiceManager 作为输入,因此您不需要Function 作为输入,而是需要BiFunction&lt;? super MyObjectJson, ? super ServiceManager, ? extends MyObject&gt;1:

private PaginatedList<MyObject> mapList(PaginatedList<MyObjectJson> paginatedList,
      BiFunction<? super MyObjectJson, ? super ServiceManager, ? extends MyObject> myObjectProducer) {
    return paginatedList.stream()
            .map(jsonObject -> myObjectProducer.apply(jsonObject, this.getServiceManager()))
            .collect(Collectors.toCollection(PaginatedList::new));
}

只需使用mapList(someList, MyObjectWrapper::new) 调用它。

1为什么super/extends,阅读What is PECS

【讨论】:

  • 这很棒并且按预期工作 - 感谢快速而彻底的响应。
猜你喜欢
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多