I'm trying to do the following: if I have an array numbers which has the numbers
{1,4,9,16,25,36,49,64,81,100}
I want to calculate recursively the differences between two succeeding elements. So first between element 1
and 0
, then 2 and
1, etc.
Once I have those differences I want to calculate the differences between any two succeeding elements in that array.
So if you start with
{1,4,9,16,25,36,49,64,81,100}
you go to
{3,5,7,9,11,13,15,17,19}
and then to
{2,2,2,2,2,2,2,2}
I know how to program this, but only in Java 7 style and not in Java 8 Lambda expression style. This was my attempt:
Integer[] numbers = new Integer[] {1,4,9,16,25,36,49,64,81,100};
for (int i=0;i<3;i++)
{
int length = numbers.length;
numbers = IntStream.range(1, length)
.mapToObj(a->numbers[a]-numbers[a-1])
.toArray(b->new Integer[length-1]);
}
This doesn't work because Java requires the array numbers to be final when using lambda expressions, but then I cannot call the same code recursively on the same array. How can I solve this?