I want to get the minimum value of a function result of an object list.
But the return value of this function is optional.
So it would be OK if no fragment time is set so far and the return value should then be Optional.empty()
public Optional<Double> getFragmentTime(int fragment) {
...
}
private List<Entry> entries; // will be filled in the ctor.
public Optional<Double> getMinFragmentTime(int fragment) {
return entries.stream()
.map(e -> e.getFragmentTime(fragment))
.filter(Optional::isPresent)
.map(Optional::get)
.min(Double::compare);
}
Is this the correct way to archive it?
The two function calls .filter(Optional.isPresent)
and .map(Optional.get)
seems rather odd to me, and I think there must be a better solution for it.
First one should use the stream for the primitive type, as that has a nice support for
min()
.An OptionalDouble may deliver a stream of 1 or 0 doubles. A flatMap to DoubleStream, and then taking the min.
(Code not verified.)