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 ?
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);
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]));
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With