Myon
Myon

Reputation: 957

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.

Upvotes: 4

Views: 1832

Answers (2)

fps
fps

Reputation: 34460

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.

Upvotes: 5

Ousmane D.
Ousmane D.

Reputation: 56453

you can use an IntStream.range to generate the indices and then operate on that.

C[] cs = (C[])IntStream.range(0, as.length)
                       .mapToObj(i -> op.apply(as[i], bs[i]))
                       .toArray();

Upvotes: 4

Related Questions