Convert a pair of doubles to 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 that are 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 doesn't matter at all, just a list of points (this is just a simple and quick example).

How to convert this list to an array of two pairs (double [] array) in Java 8?

+5
source share
4 answers

That should do it.

 points.stream() .flatMapToDouble(point -> DoubleStream.of(point.getX(), point.getY())) .toArray(); 
+7
source
 points.stream().flatMap(p -> Stream.of(px, py)).toArray(Double[]::new) 
0
source

This 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]

0
source

You can use Java threads to map each point to a list of (2) values, which then get flatMap ped to the list of values. Until you mind their boxing in Double values.

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

Source: https://habr.com/ru/post/1275139/


All Articles