Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to combine two arrays pairwise in Java 8

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.

like image 270
Myon Avatar asked Jan 04 '23 00:01

Myon


1 Answers

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.

like image 133
fps Avatar answered Jan 05 '23 15:01

fps