如何使用Java 8中的Stream将List转换为List

huangapple go评论71阅读模式
英文:

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&lt;Point[]&gt; listPoints = ...
List&lt;Quadrangle&gt; quadrangles = ...

How convert List&lt;Point[]&gt; to List&lt;Quadrangle&gt; 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&lt;Quadrangle&gt; quadrangles = listPoints.stream()
                .collect(Collectors.toCollection(o -&gt; new Quadrangle(o)));

but this doesn't work for me. I get error:

Required  type:Point[]
Provided: &lt;lambda parameter&gt;

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&lt;Quadrangle&gt; quads = listPoints.stream()
.map(Quadrangle::new)
.collect(Collectors.toList());

</details>



huangapple
  • 本文由 发表于 2020年8月31日 07:27:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63663052.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定