# Sum pairs of numbers in array

This code takes a list of ints and sums their pairs, storing the summed pairs in an array sumPairs, then returning that array. If the supplied array toSum has an odd number of elements, it returns the sumPairs with the last element of the toSum as the last element of sumPairs. Any suggestions for improving my code, or accomplishing this task in a better way, would be most appreciated!

public static int[] collapse(int[] toSum) {
int[] sumPairs = new int[toSum.length / 2 + toSum.length % 2];
for (int i = 0, j = 0; i < toSum.length - 1; i+=2, j++) {
sumPairs[j] = toSum[i] + toSum[i + 1];
}
if (toSum.length % 2 == 1 && sumPairs[sumPairs.length - 1] == 0) {
sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1];
}
return sumPairs;
}


Looks good! :)

The only thing I can spot is that the second condition for your if statement is unnecessary, as the first condition is all that is required. Therefore:

if (toSum.length % 2 == 1) {
sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1];
}


Here's a version using Java 8 streams and lambdas. I personally find it slightly more readable, but I'm sure some will disagree.

public static int[] collapse(int[] toSum) {
return IntStream.range(0, toSum.length)
.filter(n -> n % 2 == 0)
.map(n -> toSum[n] + (n + 1 == toSum.length ? 0 : toSum[n + 1]))
.toArray();
}


I'll second hjk that this is already good. This entire process is $O(N)$ and there's no getting better than that. Only thing I'd personally do in your place is add more white-space between statements for readability.

public static int[] collapse(int[] toSum) {
int[] sumPairs = new int[toSum.length / 2 + toSum.length % 2];

for (int i = 0, j = 0; i < toSum.length - 1; i+=2, j++) {
sumPairs[j] = toSum[i] + toSum[i + 1];
}

if (toSum.length % 2 == 1) {
sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1];
}

return sumPairs;
}