Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 582
ng.newbie Avatar asked May 22 '20 18:05

ng.newbie


3 Answers

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);
like image 154
Ousmane D. Avatar answered Sep 24 '22 01:09

Ousmane D.


Arrays::setAll

Demo:

import java.awt.Color;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int r[] = { 255, 255, 255 };
        int g[] = { 0, 0, 0 };
        int b[] = { 255, 255, 255 };
        Color[] arr = new Color[3];

        Arrays.setAll(arr, i -> new Color(r[i], g[i], b[i]));
        System.out.println(Arrays.toString(arr));
    }
}

Alternatively, you can use IntStream:range to iterate and fill arr.

import java.awt.Color;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
       int r[] = { 255, 255, 255 };
       int g[] = { 0, 0, 0 };
       int b[] = { 255, 255, 255 };
       Color[] arr = new Color[3];

       IntStream.range(0, arr.length).forEach(i->arr[i] = new Color(r[i], g[i], b[i]));
    }
}
like image 31
Arvind Kumar Avinash Avatar answered Sep 23 '22 01:09

Arvind Kumar Avinash


You can use IntStream.range for index sequence, and then use map for mapping into Color object and finally collect them into array

IntStream.range(0,r.length)
         .boxed()
         .map(i->new Color(r[i],g[i],b[i]))
         .toArray(Color[]::new);
like image 32
Deadpool Avatar answered Sep 22 '22 01:09

Deadpool