I am curious, how to sum up multiple variables in a java8 stream.
Integer wCPU = 0;
Double wnetwork = 0.0;
Double wMem = 0.0;
this.slaContractList.forEach(sla -> {
wCPU += sla.getNumberOfCPUs();
wnetwork += sla.getNetworkBandwith();
wMem += sla.getMemory();
});
However, this does not compile as the variable in the lambda expression should be final.
Just to do a sum, i would use the sum operation of streams just like in Łukasz answer, but, for a more general solution for resolving the "final problem" you can use the classes of java.util.concurrent.atomic. It is intented to be used in stream and is thread-safe, so could be used in a parallel stream.
Now you see that there are 2 kind of implementation: the Accumulator and the Atomic, the choice between these 2 is another question:
java 8 : Are LongAdder and LongAccumulator preferred to AtomicLong?
I would do a simple hack like this:
It's optional to have the
final
keyword for both , as in Java 8 they have introduced the effectively final concept. It means, you have assigned only once.Assuming
slaContractList
is a list ofSlaContract
objects, and it has constructorSlaContract(numberOfCPUs, networkBandwith, memory)
you can:The same solution, but for simple class:
Try to use
Stream.reduce
andStream.sum
:See https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html
The advantage of using stream is option of use
parallelStream()
instead ofstream()
. In some situations it can be more efficient than simple loop.