You probably don’t want to use Optional
for your three final variables. Optional
, OptionalDouble
and OptionalLong
are often great for return values that may not be there. For local variables in a method that is 20 lines or shorter they don’t really buy you anything. According to my taste the same goes for final
, but I acknowledge that opinions are more diverse here.
My suggestion would be (given that you want final
variables):
final Long historyHours1 = parameters.map(p -> /* some logic */).orElse(null):
final Double historyHours2 = parameters.map(p -> /* some logic */).orElse(null):
final Float historyHours3 = parameters.map(p -> /* some logic */).orElse(null):
The cost of this rewrite is that we’re testing three times whether your parameters are present. That‘s probably fine, but you will need to weigh that yourself.
In case you insist on Optional
, the same idea works:
final OptionalLong historyHours1 = parameters.stream()
.mapToLong(p -> /* some logic */)
.findAny();
Similar for the other variables. Use OptionalDouble
and OptionalLong
. And Optional<Float>
since there is no OptionalFloat
class. Even though for unboxing into OptionalLong
or OptionalDouble
we need to go via a stream as shown in the code line.
Depending on what you will be using the historyHoursX
variables for it is also possible that a rewrite involving that is possible, also a rewrite that exploits parameters
being an Optional
(when I have guessed that correctly). So you may want to show us more of your existing code.