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

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

How to convert List<FirstObject[]> to List<SecondObject> with Stream in Java 8?

问题

我有列表:

  1. List<Point[]> listPoints = ...
  2. List<Quadrangle> quadrangles = ...

如何使用 Java 8 中的 Stream 将 List<Point[]> 转换为 List<Quadrangle>

需要替换:

  1. for(Point[] groupPoints : listPoints) {
  2. quadrangles.add(new Quadrangle(groupPoints));
  3. }

Quadrangle 对象具有构造函数:

  1. public Quadrangle(Point[] points) {
  2. this.p1 = points[0];
  3. this.p2 = points[1];
  4. this.p3 = points[2];
  5. this.p4 = points[3];
  6. }

我尝试了这个:

  1. List<Quadrangle> quadrangles = listPoints.stream()
  2. .map(groupPoints -> new Quadrangle(groupPoints))
  3. .collect(Collectors.toList());

但是这对我不起作用。我得到了错误:

  1. 需要的类型Point[]
  2. 提供的类型<lambda parameter>

我认为 lambda parameter o 是数组 Point[],但实际上并不是这样。

英文:

I have lists:

  1. List&lt;Point[]&gt; listPoints = ...
  2. List&lt;Quadrangle&gt; quadrangles = ...

How convert List&lt;Point[]&gt; to List&lt;Quadrangle&gt; with Stream in Java 8?

Need replace:

  1. for(Point[] groupPoints : listPoints) {
  2. quadrangles.add(new Quadrangle(groupPoints));
  3. }

Object Quadrangle has the constructor:

  1. public Quadrangle(Point[] points) {
  2. this.p1 = points[0];
  3. this.p2 = points[1];
  4. this.p3 = points[2];
  5. this.p4 = points[3];
  6. }

I tried this:

  1. List&lt;Quadrangle&gt; quadrangles = listPoints.stream()
  2. .collect(Collectors.toCollection(o -&gt; new Quadrangle(o)));

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

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

I thought that the lambda parameter o is the array Point [], but isn't it.

答案1

得分: 2

尝试这样做:

  • 将点数组列表进行流式处理。
  • 映射到四边形的新实例(这将应用构造函数参数)。
  • 返回四边形的列表。
  1. List<Quadrangle> quads = listPoints.stream()
  2. .map(Quadrangle::new)
  3. .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.
  1. List&lt;Quadrangle&gt; quads = listPoints.stream()
  2. .map(Quadrangle::new)
  3. .collect(Collectors.toList());
  4. </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:

确定