gpt4 book ai didi

java - 创建一个组合来自并行数组的项目的流

转载 作者:行者123 更新时间:2023-12-04 12:09:04 25 4
gpt4 key购买 nike

我希望创建一个流,其中包含我在该流中实例化的对象。我对流很陌生,所以我不确定如何获取具有多个数组参数的对象并基于这些数组在流中实例化对象。
这是我试图实例化的嵌套类:

    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 - 创建一个组合来自并行数组的项目的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68402164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com