Reputation: 23
everyone.
I've faced a task, that looked pretty simple to me, but I spend like 4 hours and left with nothing. So, let's assume we have simple list of integers like
[1, 2, 3, 4, 5]
I want to get sum of subtractions for each element - for this list, it would be equal to 4 -> (2 - 1) + (3 - 2)... and so on.
To avoid answers with range, list may look like this:
[5, 12, 16, 25, 25, 48]
It's always growing, but not with the same range between.
Using simple for it's not hard to get something like:
int result = 0;
for (int i = 1; i < lst.size(); i++) {
result += lst.get(i) - lst.get(i-1);
}
But I'm feeling myself utterly stupid when I'm trying to solve this case using streams.
Is this actually possible?
Upvotes: 2
Views: 110
Reputation: 2370
Assuming you have a list of Integers like this : [ n0, n1, n2, ... , nM, nN ]
, what you're doing is :
[(n1 - n0), (n2 - n1), (n3 - n2), ..., (nN - nM)]
. X = (n1 - n0) + (n2 - n1) + (n3 - n2) + ... + (nN - nM)
.
Which is rigourously the same (just swapped the inside of parenthesises as they don't matter) as X = (-n0) + (n1 - n1) + (n2 - n2) + ... + (nM - nM) + nN ]
.Which is (as others pointed out) X = nN - n0
. No matter what is inside your list (except null).
Thus, lst.get(lst.size()-1) - lst.get(0)
is, by far, the best answer.
Upvotes: 4
Reputation: 19926
Try using this:
int result = IntStream.range(1, lst.size()) // creates a stream of indexes from 1 to lst.size()
.map(i -> lst.get(i) - lst.get(i-1)) // maps the new value into a new stream
.sum(); // sums it up
Upvotes: 2