简体   繁体   中英

How to concat two double-arrays with streams

I have two Lists:

Class Matrix: List<Stroke> stroke = new ArrayList<>();

Class Stroke: List<Point2D> points = new ArrayList<>();

Every entry of points does map to {x, y, z} :

points.stream().map(p -> new double[]{p.getX(), p.getY(), 0.0})

Every stroke gives a double[][] .

Now i want to convert the stroke list to double[][] . Since every stroke gives a double[][] something is need to concatenate every array.

How to do this with streams?

stroke.stream()....

Thanks to the answer of Patrick Parker i got an idea of how to solve this.

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 . See the relevant javadoc for details.

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 . Or, even better results with a Stream<double[]> instead of using any intermediate containers, as you discovered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM