Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream average for float

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?

like image 751
alexanoid Avatar asked Sep 16 '14 19:09

alexanoid


People also ask

How do you average a stream in Java?

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.

How do you find the average of an array in Java 8?

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.

Are Java 8 streams lazy?

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.


1 Answers

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); 
like image 177
Misha Avatar answered Sep 20 '22 08:09

Misha