Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Pair of Double into a double array

Tags:

java

java-8

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?

like image 356
alexander Avatar asked Feb 02 '18 18:02

alexander


People also ask

How do you convert double to double?

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.

Can you make an array with doubles Java?

An array is not a double, you need to select an index : double[] arr = new double[2]; System. out.

Can I use double in array?

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.


1 Answers

This should do it.

points.stream()
      .flatMapToDouble(point -> DoubleStream.of(point.getX(), point.getY()))
      .toArray();
like image 109
pvpkiran Avatar answered Sep 30 '22 11:09

pvpkiran