逐个元素对两个数组求和的最简单方法是什么?
我知道您可以使用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
在语言中肯定无法实现这一点.我也不知道标准库中的任何内容,但是将您编写的代码放入实用程序方法中是非常简单的,您可以从任何需要它的地方调用它.
还有一个答案,使用流并提供更通用的解决方案:
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)
归档时间: |
|
查看次数: |
57122 次 |
最近记录: |