java - 在 Java 11 中映射泛型集合
问题描述
我一直在尝试找到一种方法来编写泛型函数(可能不使用泛型)来映射集合。
假设我有一个函数 A 到 B,我想编写一个接受 aCollection<A>
并返回 a的函数Collection<B>
。注意 A 和 B 不是泛型,只是表达一般模式的一种方式。
到目前为止我所拥有的是
public static Collection<Point> points2dToPoints(Collection<Point2D> points) {
return points.stream()
.map(Utils::point2dToPoint)
.collect(Collectors.toCollection(() -> points));
}
但是,我在 中收到类型错误.collect
,因为显然我希望新集合成为Collection<Point>
但我不确定如何为此获取供应商?
编辑:我希望能够以通用方式使用此函数:如果我将它传递给 Set 我会得到一个 Set 作为回报,但如果我将它传递给 List 我会得到一个列表作为回报。甚至有可能做到这一点吗?
解决方案
最好的选择是不要过于复杂,只需执行以下操作:
public static Collection<Point> points2dToPoints(Collection<Point2D> points) {
return points.stream()
.map(Utils::point2dToPoint)
.collect(Collectors.toList());
}
返回接口的具体实现Collection
(例如, Collectors.toList()
),同时从外部隐藏实现细节(即,在Collection
方法签名中)。
但是,您可以通过将您希望它返回Supplier
的接口的具体实现传递给它来使您的方法更通用,即Collection
public static Collection<Point> points2dToPoints(Collection<Point2D> points, Supplier<Collection<Point>> aNew) {
return points.stream()
.map(Utils::point2dToPoint)
.collect(toCollection(aNew));
通过这种方式,您可以传递Collection
将返回的具体实现,例如:
points2dToPoints(.., ArrayList::new);
points2dToPoints(.., TreeSet::new);
推荐阅读
- android - 如何访问 `ContentCaptureManager` 数据?
- c# - 无法从 blazor 组件调用 javascript 函数
- r - 根据 R 中的值和 NA 过滤“POSIXct”“POSIXt”列
- c - 从 C 中的控制台读取一行
- c# - 取消并行进程
- reactjs - 样式化组件流体类型
- selenium - Selenium:在 Raspberry Pi 上,chrome 版本必须 >= 62
- python - 上传图片 Selenium Webdriver Python - 无法上传图片 => 错误:“无法找到元素:{“method”:“xpath”,“selector”:“”
- reactjs - 登录后无法渲染组件
- c++ - c ++如何为typedef类型制作构造函数