Skip to content
Advertisement

Convert 3 arrays into 1 object array using Streams

Lets say I have the following three arrays:

int r[] = {255,255,255};
int g[] = {0,0,0};
int b[] = {255,255,255};

All arrays will have same length.

I want to convert them into an array of objects of type Color:

public class Color {
   int r,g,b;

   public Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
   }

}

Color[] arr = new Color[3];

Where each index will contain the r,g,b from the same index from the 3 arrays. For example, lets say for Color[1] = new Color(r[1],g[1],b[1]);

How do I do that using Java Streams ?

The for-loop variant of the code is:

Color arr[] = new Color[r.length];

for(int i=0;i<r.length;i++) {
    Color c = new Color(r[i],g[i],b[i]);
    arr[i] = c;
}

Is there even a way to do this using streams ?

Advertisement

Answer

IntStream.range + mapToObj then accumulate to an array:

IntStream.range(0, r.length)
         .mapToObj(i -> new Color(r[i], g[i], b[i]))
         .toArray(Color[]::new);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement