1

I see a strange issue where eclipse is not dentifying my lambda arguments

public static void main(String[] args) {
    int[] array = {23,43,56,97,32};
    int sum1 = Arrays.asList(array).stream().reduce(0, (total, e) -> total + e).intValue(); 
}

I get total and e cannot be resolved to a variable.
I see examples where 'total' and 'e' are used as arguments without declaring.
However,in my case - it refuses to compile without declaring.
What is the issue here?

3 Answers 3

5

Arrays.asList(array) for a primitive array returns a List whose single element is that array.

Change

Arrays.asList(array).stream()

to

Arrays.stream(array)

Note this will give to an IntStream, not a Stream<Integer>, so no need for intValue() at the end:

int sum1 = Arrays.stream(array).reduce(0, (total, e) -> total + e);

For a Stream<Integer> you can write:

Arrays.stream(array).boxed()

and the full line will be:

int sum1 = Arrays.stream(array).boxed().reduce(0, (total, e) -> total + e).intValue ();

Of course you can simply obtain the sum with:

int sum1 = Arrays.stream(array).sum ();
Sign up to request clarification or add additional context in comments.

Comments

3
Arrays.asList(int[]) - will create a List<int[]>

You should have it like this:

int sum1 = Arrays.asList(23, 43, 56, 97, 32)
                 .stream().reduce(0, (total, e) -> total + e).intValue(); 

Comments

0

Simply use:

int[] array = {23,43,56,97,32};
int sum1 = Arrays.stream(array).reduce(0, (total, e) -> total + e);

I've changed Arrays.asList(...).stream(), which produces Stream<int[]>, to Arrays.stream(...) (or IntStream.of(...)).

In addition to this you can simplify the reduction to:

int sum1 = Arrays.stream(array).sum();

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.