Reputation: 9809
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?
Upvotes: 1
Views: 109
Reputation: 120858
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();
Upvotes: 3
Reputation: 11740
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();
Upvotes: 0
Reputation: 393841
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 ();
Upvotes: 5