在Java中按元素求和两个数组

I L*_*ode 14 java arrays

逐个元素对两个数组求和的最简单方法是什么?

我知道您可以使用for如下循环:

int[] a = {0, 1, 2};
int[] b = {3, 4, 5};
int[] c = new int[a.length];
for (int i = 0; i < a.length; ++i) {
    c[i] = a[i] + b[i];
}
Run Code Online (Sandbox Code Playgroud)

但是在MATLAB这样的语言中,你可以通过编写来逐个元素的数组求和c = a + b.在Java中有一种简单的方法吗?

想到的方法是使用Apache Commons Math中的RealVector类,但该方法相当冗长.

Jon*_*eet 12

语言中肯定无法实现这一点.我也不知道标准库中的任何内容,但是将您编写的代码放入实用程序方法中是非常简单的,您可以从任何需要它的地方调用它.

  • 只是我认为标准库没有像元素添加这样的东西是疯了吗?对于一种语言而言,它似乎是一种非常基本的缺失功能,它具有与Java一样多的铃声和口哨声. (3认同)

Ben*_*oit 5

还有一个答案,使用流并提供更通用的解决方案:

import org.junit.Assert;
import org.junit.Test;

import java.util.function.IntBinaryOperator;
import java.util.stream.IntStream;

public class SOTest {

    @Test
    public void test() {
        int[] a = {0, 1, 2};
        int[] b = {3, 4, 5};

        int[] sum = applyOn2Arrays((x, y) -> x + y, a, b);
        int[] diff = applyOn2Arrays((x, y) -> x - y, a, b);
        int[] mult = applyOn2Arrays((x, y) -> x * y, a, b);


        Assert.assertArrayEquals(new int [] {3,5,7}, sum);
        Assert.assertArrayEquals(new int [] {-3,-3,-3}, diff);
        Assert.assertArrayEquals(new int [] {0,4,10}, mult);
    }

    private int[] applyOn2Arrays(IntBinaryOperator operator, int[] a, int b[]) {
        return IntStream.range(0, a.length)
                .map(index -> operator.applyAsInt(a[index], b[index]))
                .toArray();
    }
}
Run Code Online (Sandbox Code Playgroud)