Java 8 average stream 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 a function that gets the average weight using Java 8 features:

public float getAvgChangedWeight() {
    return (float) weightChanges.stream().mapToDouble(WeightChange::getValue).average().getAsDouble();      
}

      

Can you please help improve it, because I don't think a great two is a good idea.

Also it throws an exception when the collection is weightChanges

empty. How can I improve it in this case?

+16


source to share


3 answers


To answer the second part of your question, if you want to avoid an exception when the list is empty and return a value double

, use orElse

instead getAsDouble

:



return weightChanges.stream()
    .mapToDouble(WeightChange::getValue)
    .average()
    .orElse(Double.NAN);

      

+46


source


Another solution,



/**
 * Compute the average of a list of BigDecimal objects
 *
 * @param bigDecimalList the list which contains the BigDecimals
 * @param roundingMode the RoundingMode to use.
 * @return a BigDecimal with the average of the list given as argument or null if the list is empty or full of null BigDecimal numbers.
 */
public BigDecimal bigDecimalAverage(List<BigDecimal> bigDecimalList, RoundingMode roundingMode) {
    // Get only the not null bigDecimals
    List<BigDecimal> bigDecimals = bigDecimalList.stream().filter(Objects::nonNull).collect(Collectors.toList());

    // Compute for the extreme cases
    if (bigDecimals.isEmpty())
        return null;
    if (bigDecimals.size() == 1)
        return bigDecimals.get(0);

    // Compute the average
    return bigDecimals.stream().reduce(ZERO, BigDecimal::add).divide(new BigDecimal(bigDecimals.size()), roundingMode);
}

      

+1


source


Your solution is perfect. Just adding .orElse (default) // to print in case no elements are found will make it complete.

0


source







All Articles