我有以下结构
public class Point {
private final double x;
private final double y;
// imagine required args constructor and getter for both fields
}
现在,我已经定义了这些点的列表。
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));
数据根本不重要,只是一个点列表(以上只是一个简单快捷的例子)。
如何以Java 8方式将此列表转换为双精度数组(double []数组)?
答案 0 :(得分:7)
这应该这样做。
points.stream()
.flatMapToDouble(point -> DoubleStream.of(point.getX(), point.getY()))
.toArray();
答案 1 :(得分:0)
points.stream().flatMap(p -> Stream.of(p.x, p.y)).toArray(Double[]::new)
答案 2 :(得分:0)
可以通过反思来实现灵活性。
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;
}
}
输出:[10.0, 11.0, 12.0, 13.0, 14.0, 15.0]
答案 3 :(得分:-2)
您可以使用Java Streams将每个点映射到(2)值列表,然后将flatMap
ped放入值列表中。只要你不介意将它们装入Double
值。
List<Double> resultList = points.toStream()
.flatMap( pt -> Arrays.asList( new Double[] { pt.x, pt.y }.toStream() )
.collect( Collectors.toList() );