[英]How to concat two double-arrays with streams
我有两个清单:
类矩阵: List<Stroke> stroke = new ArrayList<>();
类描边: List<Point2D> points = new ArrayList<>();
points
每个条目都映射到{x, y, z}
:
points.stream().map(p -> new double[]{p.getX(), p.getY(), 0.0})
每个笔画都为double[][]
。
现在我想将stroke
列表转换为double[][]
。 由于每个stroke
提供double[][]
,因此需要连接每个数组。
如何使用流执行此操作?
stroke.stream()....
多亏了帕特里克·帕克 ( Patrick Parker)的回答 ,我才有了解决该问题的想法。
我的解决方案确实是这样的:
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);
}
}
如果在代码或性能方面可能有所改进,请随时告诉我。
编辑:
再次感谢帕特里克·帕克! 我更换了
.map(StrokeManipulation::getArrayStream)
.reduce(Stream.empty(), Stream::concat)
只是
.flatMap(StrokeManipulation::getArrayStream)
我想你想要这样的东西:
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);
});
}
}
为此,我选择了终端操作reduce
。 有关详细信息,请参见相关的Javadoc 。
但是 ,我想指出的是,这并不是非常有效,因为您在每个缩减阶段都分配一个新的数组。 使用终端操作collect
可以从可变容器类(例如ArrayList)中获得更好的结果。 或者,使用Stream<double[]>
而不是您发现的任何中间容器,甚至可以获得更好的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.