首页 > 解决方案 > 在 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 我会得到一个列表作为回报。甚至有可能做到这一点吗?

标签: javagenericscollectionsjava-11

解决方案


最好的选择是不要过于复杂,只需执行以下操作:

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);

推荐阅读