创建一个组合来自并行数组的项目的流
Create a stream that combines items from parallel arrays
我想创建一个流来保存我在该流中实例化的对象。我对流很陌生,所以我不确定如何获取具有多个数组参数的对象并基于这些数组在流中实例化对象。
这是一个嵌套的 class 我正在尝试实例化:
public static class Stats{
public final double time;
public final double pace;
public final double rating;
public final double height;
//this is a nested class that contains
//latitude and longitude double fields
public final LatLon position;
public Stats(double time, double pace, double rating, double height, LatLon position) {
super();
this.time= time;
this.pace= pace;
this.rating= rating;
this.height= height;
this.position= position;
}
//getters and setters
这是主要的class,我想在“tripStats”方法中实例化和流式传输对象:
public class Trip{
//These arrays will be created via a JSON file
public final double[] time;
public final double[] pace;
public final double[] rating;
public final double[] height;
public final LatLng[] position;
public Stream<Stats> tripStats(){
//I'm not sure if I should create a stream of streams or use the
//array instance variables to begin constructing this stream.
//I'm trying to create Stats objects here using this stream
return Stream.of(time, pace, rating, height, position)
.map(value -> {
Stats stats = new Stats(???);
return stats;});
}
您可以使用 IntStream
个索引并将它们映射到各自的参数:
public Stream<Stats> tripStats() {
return IntStream.range(0, time.length) // assumes they're all the same length
.mapToObj(i -> new Stats(time[i], pace[i], rating[i], height[i], position[i]));
}
我想创建一个流来保存我在该流中实例化的对象。我对流很陌生,所以我不确定如何获取具有多个数组参数的对象并基于这些数组在流中实例化对象。
这是一个嵌套的 class 我正在尝试实例化:
public static class Stats{
public final double time;
public final double pace;
public final double rating;
public final double height;
//this is a nested class that contains
//latitude and longitude double fields
public final LatLon position;
public Stats(double time, double pace, double rating, double height, LatLon position) {
super();
this.time= time;
this.pace= pace;
this.rating= rating;
this.height= height;
this.position= position;
}
//getters and setters
这是主要的class,我想在“tripStats”方法中实例化和流式传输对象:
public class Trip{
//These arrays will be created via a JSON file
public final double[] time;
public final double[] pace;
public final double[] rating;
public final double[] height;
public final LatLng[] position;
public Stream<Stats> tripStats(){
//I'm not sure if I should create a stream of streams or use the
//array instance variables to begin constructing this stream.
//I'm trying to create Stats objects here using this stream
return Stream.of(time, pace, rating, height, position)
.map(value -> {
Stats stats = new Stats(???);
return stats;});
}
您可以使用 IntStream
个索引并将它们映射到各自的参数:
public Stream<Stats> tripStats() {
return IntStream.range(0, time.length) // assumes they're all the same length
.mapToObj(i -> new Stats(time[i], pace[i], rating[i], height[i], position[i]));
}