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?
To convert double primitive type to a Double object, you need to use Double constructor. Let's say the following is our double primitive. // double primitive double val = 23.78; To convert it to a Double object, use Double constructor.
An array is not a double, you need to select an index : double[] arr = new double[2]; System. out.
In case it isn't clear, your array cannot be of double length. It's undefined behavior. This is because a double is not an integer, but a rational number that could be an integer.
This should do it.
points.stream()
.flatMapToDouble(point -> DoubleStream.of(point.getX(), point.getY()))
.toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With