Reputation: 1277
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).
Upvotes: 0
Views: 475
Reputation: 1461
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());
Upvotes: 0
Reputation: 6729
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) ]
Upvotes: 1
Reputation: 393856
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.
Upvotes: 0