在Java 8中成对组合两个数组的优雅方式

时间:2021-12-21 12:19:44

I like to combine two generic arrays pairwise by a BiFunction. Here you see the naive implementation:

我想通过BiFunction成对组合两个通用数组。在这里你看到了天真的实现:

<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.

我想知道在没有for循环的情况下是否有更优雅的方法来实现这一点 - 也许使用Java 8 Stream。我很高兴你的建议。

2 个解决方案

#1


5  

You can use Arrays.setAll method:

您可以使用Arrays.setAll方法:

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.

或者,如果op的计算成本非常高,您也可以使用Arrays.parallelSetAll。

#2


3  

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

您可以使用IntStream.range生成索引,然后对其进行操作。

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

#1


5  

You can use Arrays.setAll method:

您可以使用Arrays.setAll方法:

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.

或者,如果op的计算成本非常高,您也可以使用Arrays.parallelSetAll。

#2


3  

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

您可以使用IntStream.range生成索引,然后对其进行操作。

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