I like to combine two generic arrays pairwise by a BiFunction
. Here you see the naive implementation:
<A,B,C> C[] combine(A[] as, B[] bs, BiFunction<A,B,C> op) {
if (as.length == bs.length) {
C[] cs = (C[]) new Object[as.length];
for(int i = 0; i < as.length; i++) {
cs[i] = op.apply(as[i], bs[i]);
}
return cs;
} else {
throw new IllegalArgumentException();
}
}
I wonder if there is a more elegant way to do this without a for-loop - maybe with Java 8 Stream
. I would be happy about your suggestions.
You can use Arrays.setAll
method:
C[] cs = (C[]) new Object[as.length];
Arrays.setAll(cs, i -> op.apply(as[i], bs[i]));
Or, if op
is very expensive to compute, you can also use Arrays.parallelSetAll
.
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