TDa
TDa

Reputation: 9

How stream in Java 8 calculate on item in array by index

I am new to Java 8 and I am studying streams and have a problem that I can't solve:

int[] intArr = new {1,2,4,6,7,8};

I want to use a Stream to get the items in odd positions in array.

Expected result : [1,4,7]

And use a Stream to generate a new array that is formed by: {intArr[i] + intArr[i+1]}

Expected result: [3,6,10,13,15]

Upvotes: 0

Views: 739

Answers (1)

Holger
Holger

Reputation: 298143

Your question is a bit confusing as you are asking two unrelated questions at once and use wrong terminology.

You first question:

Since Java starts indexing array with zero, you are not asking for the odd indexes but rather even:

int[] intArr = {1,2,4,6,7,8};
int[] even=IntStream.range(0, (intArr.length+1)/2).map(i->intArr[i*2]).toArray();
System.out.println(Arrays.toString(even));

[1, 4, 7]

As said, your second question is confusing because it looks like your want to use the result of the first one, somehow, but it turns out to be completely unrelated. If you want to add the follow-up number to each number, you just need a stream iterating each index but the last one:

int[] result=IntStream.range(0, intArr.length-1)
            .map(i -> intArr[i]+intArr[i+1]).toArray();
System.out.println(Arrays.toString(result));

[3, 6, 10, 13, 15]

Upvotes: 5

Related Questions