0

I'm trying to sum an array of Integers. I red @ZouZou 's solution from this question and can't get it to work

int [] arr = {1,2,3,4};
int sum = Arrays.stream(arr).sum(); //prints 10

I've got

public static void proc(Integer[] v) {
    int sum = Arrays.stream(v).sum();

and the compiler gives "cannot find symbol method sum".

What is the problem? Is doing it this way any faster than summing with a loop?

Community
  • 1
  • 1
Celeritas
  • 14,489
  • 36
  • 113
  • 194

2 Answers2

5

Arrays.stream has few overloaded versions.

Arrays.stream(int[] arr) returns IntStream which has sum method

while

Arrays.stream(T[] arr) returns Stream<T> (where T is generic) which has no sum method.

Since you are using Integer[] as argument Arrays.stream(T[] arr) is invoked which is why compiler informs you about lack of sum method.

What you can do here is either changing used type to int[] or using something like

int sum = Arrays.stream(v).reduce(Integer::sum).orElse(0);

Since reduce returns Optional<Integer> I could use get() to read its value but this way I would risk

java.util.NoSuchElementException: No value present

in case of no elements to stream on (when array is empty like new Integer[0]). In this case it is better to use orElse(0) which means: return stored value or 0 if there is no value.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • what is a reduction operation? – Celeritas Jun 06 '14 at 17:55
  • That is broad topic. I suggest reading http://docs.oracle.com/javase/tutorial/collections/streams/reduction.html. In short reduction lets you return some new result based on elements in stream. – Pshemo Jun 06 '14 at 17:57
0

Arrays.stream(v) returns a Stream<Integer> because v is an array of Integer's. There is no sum() for Stream<T> - take a look here.

If v was int[], then Arrays.stream(v) would return an IntStream which contains the sum() method you're looking for.

Hope this clarifies what's going on.

sh4nkc
  • 338
  • 1
  • 9