Java arrays total 2

Given that I have two arrays in Java, Aand BI want to add elements associated with the elements, which leads to the sum array. Doing it implicitly with a loop is easy, but I was wondering if there was a more elegant solution, perhaps with guava collections or java utils assembly. Or perhaps the python-ish method, which is simplified with a list view.

Example:

A   = [2,6,1,4]
B   = [2,1,4,4]
sum = [4,7,5,8]
+4
source share
2 answers

You can do it as follows:

private void sum() {
    int a[] = {2, 6, 1, 4};
    int b[] = {2, 1, 4, 4};

    int result[] = new int[a.length];
    Arrays.setAll(result, i -> a[i] + b[i]);
}

First, the int result[]correct size is created .

Then, with the release of Java 8 yesterday, the easy part appeared:

  • You can do Arrays.setAll(int[] array, IntUnaryOperator);
  • IntUnaryOperator lambda, , map i to a[i] + b[i], .
  • Arrays.parallelSetAll
+16

java8 :

//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...
int[] result = new int[a.length];
IntStream.range(0, a.length)
     .forEach(i -> result[i] = a[i] + b[i]);

java8

+1

Source: https://habr.com/ru/post/1532442/


All Articles