简体   繁体   English

将双精度对转换为双精度数组

[英]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? 如何以Java 8方式将此列表转换为双精度数组(double []数组)

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] 输出: [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. 您可以使用Java Streams将每个点映射到(2)个值的列表,然后将flatMap放入值列表中。 As long as you don't mind boxing them into Double values. 只要您不介意将它们装在Double值中即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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