How can I write the following in Java 8 streams?
int total = 0;
for (ObjectA obja : rootObj.getListA()) {
for (ObjectB objb : obja.getListB()) {
total += objb.getCount() * obja.getCount();
}
}
return total;
How can I write the following in Java 8 streams?
int total = 0;
for (ObjectA obja : rootObj.getListA()) {
for (ObjectB objb : obja.getListB()) {
total += objb.getCount() * obja.getCount();
}
}
return total;
Here's an alternative solution which might be preferable in a number of cases:
Fairly easy : map
ObjectA
to the sum of all itsObjectB::getCount
multiplied by its owngetCount()
, then simply sum theIntStream
:To improve readability you can introduce a private helper method :
with helper method :
The canonical solution for converting nested
for
loops toStream
API usage is viaflatMap
:This allows you to perform an operation for each inner iteration. However, in the special case of summing you may simplify the operation as it doesn’t matter whether you compute
(a+b+c+d)
or(a+b)+(c+d)
:And when we are at remembering elementary arithmetics we should also recall that
(a*x)+(b*x)
is equal to(a+b)*x
, in other words, there is no need to multiply every item ofListB
with the count ofobjA
as we can also just multiple the resulting sum with that count:And for the more general solution of walking two streams at once there's this not-very-nice but it works solution.