I have a stream calculating average costs the code looks something like this
private Double calculateAverageCost(List<Item> items) {
return items.stream()
.mapToDouble(item -> item.cost)
.filter(cost -> cost > 0) // Ignore zero cost items
.average()
. // Something here to convert an OptionalDouble to value or null
}
I need the method to return the value or null if there is no value (e.g. when all costs are zero). My problem is there is no orElseNull method on OptionalDouble to do the conversion. I can do it in another step e.g.
private Double calculateAverageCost(List<Item> items) {
final OptionalDouble average = items.stream()
.mapToDouble(item -> item.cost)
.filter(cost -> cost > 0) // Ignore zero cost items
.average();
return average.isPresent() ? average.getAsDouble() : null;
}
I realise this is a "primitive" stream and my method is returning boxed Double but it would seem like this could be helpful, similar to (Optional.empty().orElseGet(null)).
Is there a reason or a better solution im missing?