简体   繁体   中英

Converting Pair of Double into a double array

I got the following structure

public class Point {
private final double x;
private final double y;
// imagine required args constructor and getter for both fields
}

Now, I have a list of those points defined.

List<Point> points = new ArrayList<>();
points.add(new Point(0,0));
points.add(new Point(0,1));
points.add(new Point(0,2));
points.add(new Point(0,3));

The data does not matter at all, just a list of points (the above is just an easy and quick example).

How can I transform this list to a array of doubles (double[] array) in a Java 8 way?

This should do it.

points.stream()
      .flatMapToDouble(point -> DoubleStream.of(point.getX(), point.getY()))
      .toArray();
points.stream().flatMap(p -> Stream.of(p.x, p.y)).toArray(Double[]::new)

It can be done by reflection for flexibility.

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.DoubleStream;

public class DoubleReflection {

    public static void main(String[] args) throws Exception {
        List<Point> points = new ArrayList<Point>();
        points.add(new Point(10, 11));
        points.add(new Point(12, 13));
        points.add(new Point(14, 15));

        double[] array = points.stream().flatMapToDouble((row) -> {
            Field[] fields = row.getClass().getDeclaredFields();
            return Arrays.stream(fields).flatMapToDouble(field -> {
                try {
                    field.setAccessible(true);
                    return DoubleStream.of(field.getDouble(row));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                    return null;
                }
            });

        }).toArray();
        System.out.println(Arrays.toString(array));

    }

}

class Point {
    public double a;
    private double b;

    public Point(double a, double b) {
        this.a = a;
        this.b = b;
    }
    public double getB() {
        return b;
    }
}

Output: [10.0, 11.0, 12.0, 13.0, 14.0, 15.0]

You can use Java Streams to map each point to a list of (2) values, which then get flatMap ped into a list of values. As long as you don't mind boxing them into Double values.

List<Double> resultList = points.toStream()
  .flatMap( pt -> Arrays.asList( new Double[] { pt.x, pt.y }.toStream() )
  .collect( Collectors.toList() );

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