[英]How to concat two double-arrays with streams
I have two Lists: 我有两个清单:
Class Matrix: List<Stroke> stroke = new ArrayList<>();
类矩阵: List<Stroke> stroke = new ArrayList<>();
Class Stroke: List<Point2D> points = new ArrayList<>();
类描边: List<Point2D> points = new ArrayList<>();
Every entry of points
does map to {x, y, z}
: points
每个条目都映射到{x, y, z}
:
points.stream().map(p -> new double[]{p.getX(), p.getY(), 0.0})
Every stroke gives a double[][]
. 每个笔画都为double[][]
。
Now i want to convert the stroke
list to double[][]
. 现在我想将stroke
列表转换为double[][]
。 Since every stroke
gives a double[][]
something is need to concatenate every array. 由于每个stroke
提供double[][]
,因此需要连接每个数组。
How to do this with streams? 如何使用流执行此操作?
stroke.stream()....
Thanks to the answer of Patrick Parker i got an idea of how to solve this. 多亏了帕特里克·帕克 ( Patrick Parker)的回答 ,我才有了解决该问题的想法。
My solution does look like this: 我的解决方案确实是这样的:
class Stroke {
List<Point2D> points;
public Stream<double[]> getArrayStream(){
return points.stream().map(p -> new double[]{p.getX(), p.getY(), 0.0});
}
}
class Matrix {
List<Stroke> stroke;
private double[][] getArray() {
return strokeManipulationList.stream()
.flatMap(StrokeManipulation::getArrayStream)
.toArray(double[][]::new);
}
}
If there are possible improvements regarding code or performance, please feel free to let me know. 如果在代码或性能方面可能有所改进,请随时告诉我。
Edit: 编辑:
Thanks to Patrick Parker again! 再次感谢帕特里克·帕克! I replaced the 我更换了
.map(StrokeManipulation::getArrayStream)
.reduce(Stream.empty(), Stream::concat)
with just 只是
.flatMap(StrokeManipulation::getArrayStream)
I imagine you want something like this: 我想你想要这样的东西:
class Stroke {
List<Point2D> points;
double[][] toArray() {
return points.stream()
// this part you already knew how to do
.map(p -> new double[]{p.getX(), p.getY(), 0.0})
.toArray(double[][]::new);
}
}
class Matrix {
List<Stroke> stroke;
double[][] toArray() {
return stroke.stream()
.map(Stroke::toArray)
// next we will reduce the stream of double[][] to one...
.reduce(new double[][]{}, (a,b) -> {
// ...by concatenating each double[][] with its neighbor
return Stream.concat(Arrays.stream(a), Arrays.stream(b))
.toArray(double[][]::new);
});
}
}
For this task, I have chosen the terminal operation reduce
. 为此,我选择了终端操作reduce
。 See the relevant javadoc for details. 有关详细信息,请参见相关的Javadoc 。
However , I would like to point out that this will not be very efficient since you are allocating a fresh array at every reduction stage. 但是 ,我想指出的是,这并不是非常有效,因为您在每个缩减阶段都分配一个新的数组。 You could probably get better results from a mutable container class (such as an ArrayList) using the terminal operation collect
. 使用终端操作collect
可以从可变容器类(例如ArrayList)中获得更好的结果。 Or, even better results with a Stream<double[]>
instead of using any intermediate containers, as you discovered. 或者,使用Stream<double[]>
而不是您发现的任何中间容器,甚至可以获得更好的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.