As a refactoring exercise, I'm trying to take something like this:
for (int i = 1; i < orderedList.size(); i++) {
Object object1 = ordered.get(i - 1);
Object object2 = ordered.get(i);
if (isDifferent(object1, object2)) return true;
}
return false;
into a simple Java functional statement. At first glance, I'm processing elements of a list sequentially, so reduce()
sounded promising, but
- It would require carrying along a boolean value, which loses me the previous element; or
- carrying along the previous element of the list, which means I need to put it in some kind of wrapper object, or kludgy use of
Optional
or anotherList
as a wrapper, in order to keep track of whether I have a difference or not.
So, I see ways I can use a reduce operation, but it would be more complicated and hard to understand than the for-loop original.
I looked at creating a custom collector, but ran into the same issues.
Is this a proper use of reduce, or am I just tempted because I know I can use it to process sequential values against a previous iteration? If it's a proper use, how can I compose the functions to reduce myself to a boolean?
Thanks for help with this thought exercise.