0

I have an ArrayList of Integer.

a = {1, 2, 3, 4, 5}
b = {6, 7, 8, 9, 10}

I want to add the elements of the 2 arrays. So, the new array will now be: c = {7, 9, 11, 13, 15} which is (1+6), (2+7), (3+8) and so on.

Is there a way to do this without a for loop? I am looking for something like a.add(b).

chris yo
  • 1,187
  • 4
  • 13
  • 30

3 Answers3

1

You could use something like (0..<a.size).map[ idx | a.get(idx) + b.get(idx) ].toList

If you want to work with arrays, it'll look like this:

val int[] a = #[1, 2, 3, 4, 5]
val int[] b = #[6, 7, 8, 9, 10]
val int[] sums = (0..<a.length).map[ idx | a.get(idx) + b.get(idx) ]
Sebastian Zarnekow
  • 6,609
  • 20
  • 23
0

You can do it with Streams API (Java 8) :

List<Integer> c = IntStream.range(0,a.size())
                           .map(i -> a.get(i) + b.get(i))
                           .boxed()
                           .collect(Collectors.toList());

I'm not sure if it's shorter then a for loop though.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

With Java 8, you can try this way:

List<Integer> c = IntStream.range(0, a.size())
                .mapToObj(i -> a.get(i) + b.get(i))
                .collect(Collectors.toList());

If your variables type is array then:

int[] a = {1, 2, 3, 4, 5};
int[] b = {6, 7, 8, 9, 10};

List<Integer> c = IntStream.range(0, a.length)
                .mapToObj(i -> a[i] + b[i])
                .collect(Collectors.toList());
Estimate
  • 1,421
  • 1
  • 18
  • 31