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;
}
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).
Fortunately, you can assign lambda expressions to variables and reuse them, as you would with objects.
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.
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.
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:
return inputs.Sum();
as opposed to using the ForEach
extension method to sum the elements of a given list.inputs.stream().forEach(...);
in java you should instead do inputs.forEach(...)
as all lists have a forEach
method.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With