首页 > 解决方案 > 创建一个组合并行数组中的项目的流

问题描述

我正在寻找一个流来保存我在该流中实例化的对象。我对流很陌生,所以我不确定如何获取具有多个数组参数的对象并基于这些数组在流中实例化对象。

这是我要实例化的嵌套类:

    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;});

}

标签: javajava-8java-stream

解决方案


您可以使用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]));
}

推荐阅读