英文:
How to convert List<FirstObject[]> to List<SecondObject> with Stream in Java 8?
问题
我有列表:
List<Point[]> listPoints = ...
List<Quadrangle> quadrangles = ...
如何使用 Java 8 中的 Stream 将 List<Point[]> 转换为 List<Quadrangle>?
需要替换:
for(Point[] groupPoints : listPoints) {
    quadrangles.add(new Quadrangle(groupPoints));
}
Quadrangle 对象具有构造函数:
public Quadrangle(Point[] points) {
    this.p1 = points[0];
    this.p2 = points[1];
    this.p3 = points[2];
    this.p4 = points[3];
}
我尝试了这个:
List<Quadrangle> quadrangles = listPoints.stream()
    .map(groupPoints -> new Quadrangle(groupPoints))
    .collect(Collectors.toList());
但是这对我不起作用。我得到了错误:
需要的类型:Point[]
提供的类型:<lambda parameter>
我认为 lambda parameter o 是数组 Point[],但实际上并不是这样。
英文:
I have lists:
List<Point[]> listPoints = ...
List<Quadrangle> quadrangles = ...
How convert List<Point[]> to List<Quadrangle> with Stream in Java 8?
Need replace:
for(Point[] groupPoints : listPoints) {
            quadrangles.add(new Quadrangle(groupPoints));
}
Object Quadrangle has the constructor:
public Quadrangle(Point[] points) {
        this.p1 = points[0];
        this.p2 = points[1];
        this.p3 = points[2];
        this.p4 = points[3];
    }
I tried this:
List<Quadrangle> quadrangles = listPoints.stream()
                .collect(Collectors.toCollection(o -> new Quadrangle(o)));
but this doesn't work for me. I get error:
Required  type:Point[]
Provided: <lambda parameter>
I thought that the lambda parameter o is the array Point [], but isn't it.
答案1
得分: 2
尝试这样做:
- 将点数组列表进行流式处理。
 - 映射到四边形的新实例(这将应用构造函数参数)。
 - 返回四边形的列表。
 
List<Quadrangle> quads = listPoints.stream()
    .map(Quadrangle::new)
    .collect(Collectors.toList());
英文:
Try it like this.
- Stream the list of point arrays.
 - Map to a new instance of Quadrangle (this applies the constructor argument)
 - return a list of Quadrangle.
 
List<Quadrangle> quads = listPoints.stream()
.map(Quadrangle::new)
.collect(Collectors.toList());
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论