Create a stream that combines items from parallel arrays

Viewed 57

I am looking to create a stream that holds objects that I instantiate within that stream. I'm very new to streams so I'm not sure how to take an object with multiple array parameters and instantiate objects in a stream based on these arrays.

Here is a nested class I'm trying to instantiate:

    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

Here is the main class where I'd like to instantiate and stream the objects within the "tripStats" method:

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

}
1 Answers

You can use an IntStream of indexes and map them to their respective arguments:

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