I have the following model:
public class WeightChange { private float value; public float getValue() { return value; } public void setValue(float value) { this.value = value; } }
and collection:
private List<WeightChange> weightChanges;
I have implemented function that gets average weight value using Java 8 features:
public float getAvgChangedWeight() { return (float) weightChanges.stream().mapToDouble(WeightChange::getValue).average().getAsDouble(); }
Could you please help improve it because I don't think that casting to double is a good idea.
Also it throws an exception when the weightChanges
collection is empty. How does one improve it in this case?
IntStream average() method in JavaThe average() method of the IntStream class in Java returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. It gets the average of the elements of the stream.
First, create an array with values and run. the for loop to find the sum of all the elements of the array. Finally, divide the sum with the length of the array to get the average of numbers.
The Java 8 Streams API is fully based on the 'process only on demand' strategy and hence supports laziness. In the Java 8 Streams API, the intermediate operations are lazy and their internal processing model is optimised to make it being capable of processing the large amount of data with high performance.
To answer the second part of your question, if you want to avoid the exception when the list is empty and return some double
value, use orElse
instead of getAsDouble
:
return weightChanges.stream() .mapToDouble(WeightChange::getValue) .average() .orElse(Double.NaN);
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