Sum of subtractions using Java Stream API -
everyone.
i've faced task, looked pretty simple me, spend 4 hours , left nothing. so, let's assume have simple list of integers
[1, 2, 3, 4, 5]
i want sum of subtractions each element - list, equal 4 -> (2 - 1) + (3 - 2)... , on.
to avoid answers range, list may this:
[5, 12, 16, 25, 25, 48]
it's growing, not same range between.
using simple for it's not hard like:
int result = 0; (int = 1; < lst.size(); i++) { result += lst.get(i) - lst.get(i-1); } but i'm feeling myself utterly stupid when i'm trying solve case using streams.
is possible?
assuming have list of integers : [ n0, n1, n2, ... , nm, nn ], you're doing :
- create list
[(n1 - n0), (n2 - n1), (n3 - n2), ..., (nn - nm)]. - sum list :
x = (n1 - n0) + (n2 - n1) + (n3 - n2) + ... + (nn - nm). rigourously same (just swapped inside of parenthesises don't matter)x = (-n0) + (n1 - n1) + (n2 - n2) + ... + (nm - nm) + nn ].
which (as others pointed out) x = nn - n0. no matter inside list (except null).
thus, lst.get(lst.size()-1) - lst.get(0) is, far, best answer.
Comments
Post a Comment