First of all, there is no sense in using boxed Long
values and even if you once need a boxed value, you don’t need to invoke Long.valueOf
, Java already does that for you when converting a long
primitive to a boxed Long
object.
Further, since adding long
values does not depend on the order of summands, there is no reason to maintain two variable throughout the operation, when you will add them at the end anyway:
long result=0;
for(FirstLevel first: Levels) {
result += getSomeValue(first);
for(SecondLevel second: first.getSecondLevels()) {
result += getSomeValue(second);
}
}
return result;
Note that the operator +=
does the same as result = result + …
here, but avoids the repetition of the target operand.
Assuming that both, Levels
and the result of getSecondLevels
, are collections you can write the same as Stream operation as
return Levels.stream()
.mapToLong(first ->
getSomeValue(first) + first.getSecondLevels().stream()
.mapToLong(second -> getSomeValue(second)).sum())
.sum();
or, alternatively
return Levels.stream()
.flatMapToLong(first -> LongStream.concat(
LongStream.of(getSomeValue(first)),
first.getSecondLevels().stream().mapToLong(second -> getSomeValue(second))))
.sum();
If Levels
is an array, you have to replace Levels.stream()
with Arrays.stream(Levels)
and likewise, if getSecondLevels()
returns an array, you have to replace first.getSecondLevels().stream()
with Arrays.stream(first.getSecondLevels())