Reputation: 23
Suppose i have one method which takes two arrays of double type than takes a local variable 'sum' of double type with init value of zero. After that a for loop iterates from start to end and subtract like this a1[i] - b[i] and save result into another local variable called minus. Than do minus * minus and sum it with the existing value in sum variable and at the end sum. I am confuse how can i implement this in java 8 using streams. Can anybody help me?
public double calculate(double[] a1, double[] b2, int start, int end) {
double sum = 0.0;
for(int i = start; i < end; i++) {
final double minus = a1[i] - b2[i];
sum += minus * minus;
}
return sum;
}
Upvotes: 2
Views: 78
Reputation: 121048
return IntStream.range(start, end)
.mapToDouble(x -> a1[x] - b2[x])
.map(x -> x * x)
.sum();
Upvotes: 5