java - 创建一个组合并行数组中的项目的流
问题描述
我正在寻找一个流来保存我在该流中实例化的对象。我对流很陌生,所以我不确定如何获取具有多个数组参数的对象并基于这些数组在流中实例化对象。
这是我要实例化的嵌套类:
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
这是我想在“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]));
}
推荐阅读
- java - 如何将图像从 picasso 加载到 subsampling-scale-image-view ..请任何人都可以简化这一点?
- python - 如何根据包含的字符串合并两个数据框?
- perl - 第一种模式的正则表达式匹配Perl
- python - 如何每分钟自动导入csv文件(从本地电脑)(与我的电脑时钟同步)
- flutter - 无法在颤动中截取屏幕截图
- python - 检查一个数字是否在同一个数字之前,但没有从代码中得到任何输出
- c# - .NET Core EF,清理 SqlConnection.CreateCommand
- flutter - 使用类参数传递 BlocProvider
- django - 两种形式一个视图 - 值不是来自表单 - Django
- java - 迭代批次值并根据包含的值路由它们