5

The following snippet does not compile. How to find the sum using forEach as shown below?

private int Sum(ArrayList<Integer> inputs) {
    int sum = 0;

    inputs.stream().forEach(x -> sum += x);

    return sum;
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165
  • @Pau The line `inputs.stream().mapToInt(Integer::intValue).sum();` is found in both accepted answers at the moment. The question in both cases is how to find the sum of a `List` of integers using `forEach`. Why is it not a duplicate? – GBlodgett Oct 13 '18 at 20:30

2 Answers2

14

This should do the trick:

private int Sum(ArrayList<Integer> inputs) {

  return inputs.stream().mapToInt(Integer::intValue).sum();

}

EDIT :

The problem with using for-each is that it is a terminal operation, which means that it doesn't produce another intermediate stream for us to work on. The better approach would be to use mapToInt which produces an IntStream on which we can easily find the sum.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
5

This answer is just to provide a bit more context as to why your code doesn't work and therefore allowing you to decipher the problem if it were to happen in the future.

It seems like you're a .NET user which makes it completely understandable for one to expect the code you've written to work. As in .NET the equivalent would be:

private int Sum(List<int> inputs) {
        int sum = 0;
        inputs.ForEach(x => sum += x);
        return sum;
}

However, in java variables used in a lambda expression must be final or effectively final, for that reason the statement inputs.stream().forEach(x -> sum += x); will not compile.

Nevertheless, simply because one would expect the aforementioned code to work in C# doesn't necessarily mean it should work in Java as there are different rules.

There are solutions available to find the sum of a set of numbers using the forEach method but it's not the idiomatic approach and so should be avoided unless necessary.

The idiomatic approach is as @Nicholas K has shown.

On another note:

  • even in .NET the idiomatic approach would be return inputs.Sum(); as opposed to using the ForEach extension method to sum the elements of a given list.
  • whenever you seem to see yourself use inputs.stream().forEach(...); in java you should instead do inputs.forEach(...) as all lists have a forEach method.
  • method names in Java should be camelCase as opposed to PascalCasing as in C#.
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126