Reputation:
import java.util.*;
import java.util.stream.*;
class Test {
public static void main (String [] args) {
int numbers[] = {1,2,3};
List<Integer> solution = new ArrayList<Integer>();
for(int i = 0; i < numbers.length; i++) {
int temp= 0;
for(int j = 0; j < numbers.length; j ++) {
if (i == j) continue;
temp += numbers[i] + numbers[j];
}
solution.add(temp);
}
System.out.println(solution);
}
}
ex: [1,2,3] = [ (1 + 2) + (1 + 3), (2 + 1) + (2 + 3), (3 + 2) + (3 + 1)] = [7, 8, 9]
Essentially, this sums every other element in the list. How can I write this using only Java Streams?
Upvotes: 0
Views: 640
Reputation: 140318
Each output element is (sum of list) + (length of list - 2) * (input element)
.
So, calculate the sum:
int sum = IntStream.of(numbers).sum();
Then:
List<Integer> solution =
IntStream.of(numbers)
.map(e -> sum + (numbers.length - 2) * e)
.boxed()
.collect(Collectors.toList());
Upvotes: 3