0

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]

1 Answer 1

5

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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.