Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find sum with forEach and lambda expression in Java? [duplicate]

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;
}
like image 588
xport Avatar asked Oct 13 '18 16:10

xport


People also ask

Is lambda expression faster than forEach?

Here I/O operation ( println ) is much slower than all possible overhead of calling lambda or creating an iterator. In general forEach might be slightly faster as it does everything inside the single method without creating the Iterator and calling hasNext and next (which is implicitly done by for-each loop).

Can lambda expression be reused?

Fortunately, you can assign lambda expressions to variables and reuse them, as you would with objects.

Is forEach a lambda?

forEach(name -> System. out. println(name)); Since the introduction of Lambda expressions in Java 8, this is probably the most common way to use the forEach method.


2 Answers

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.

like image 158
Nicholas Kurian Avatar answered Sep 28 '22 00:09

Nicholas Kurian


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#.
like image 26
Ousmane D. Avatar answered Sep 27 '22 23:09

Ousmane D.