I am trying to find a clean and code-efficient way to convert Optional<Integer>
to Optional<Long>
. I am working in Java 7 with Guava.
So in one place in the code I have an optional integer created
Optional<Integer> optionalInt = Optional.fromNullable(someInt);
And in another area I need it as an optional long. The nicest thing I could come up with is this:
Optional<Long> optionalLong = optionalInt.transform(new Function<Integer, Long>() { @Override public Long apply(Integer inputInt) { if (inputInt != null) return inputInt.longValue(); else return null; } });
But this is cumbersome, especially if you consider how easy it was to cast the type when I was using primitive types.
Any good ideas out there?
To convert an Optional to an Integer, it is necessary to invoke the get() method before the conversion. Show activity on this post. You see, Integer. valueOf and Integer.
In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .
What is the ofNullable() method of the Optional class? The ofNullable() method is used to get an instance of the Optional class with a specified value. If the value is null , then an empty Optional object is returned.
Sadly this is the best Java 7 has to offer in terms of support for functions.
I would just say that transform
will never be called with null
so you can do:
Optional<Long> optionalLong = optionalInt.transform(new Function<Integer, Long>() { @Override public Long apply(Integer inputInt) { return inputInt.longValue(); } });
From the documentation:
If the instance is present, it is transformed with the given
Function
; otherwise,absent()
is returned. If the function returnsnull
, aNullPointerException
is thrown.
So never return null
from a Function
passed to transform
.
If you reuse this a lot, then you could use the enum
singleton pattern:
public enum IntToLong implements Function<Integer, Long> { INSTANCE; @Override public Long apply(Integer input) { return input.longValue(); } }
Then:
optionalInt.transform(IntToLong.INSTANCE);
This obviously reduces the code at the call site at the expense of having extra classes in the code base - something I wouldn't be too worried about.
close to the cast:
Optional<Long> optionalLong = Optional.fromNullable(optionalInt.isPresent() ? optionalInt.get().longValue() : null);
basically this avoids the overhead of invoking transform. Invoking isPresent could be simplified to checking the value for null directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With