I am trying to check if the input is null then output should be null Or if the input is String, then it should convert it to Long
Assuming input is never "abcd", input is either null or "12", "14", etc.
The following code snippet throws null pointer exception, as I am not able to use Java 8 Optional properly. I can catch the null pointer exception or use if/else with tertiary'?' operator but Is there any way to handle this scenario with Optional?
public class OptionalClass {
public void methodA(String input) {
System.out.println(Long.valueOf(Optional.ofNullable(input).orElse(null)));
}
public static void main(String[] args) {
new OptionalClass().methodA("12");// This works fine
new OptionalClass().methodA(null); // This throws null pointer exception
} }
Use map
to convert from Optional<String>
to Optional<Long>
:
Optional<String> str = ...;
Optional<Long> num = str.map(Long::valueOf);
If str
was empty, num
is also empty. If str
had a value, num
contains the result of valueOf
. This would mainly be useful if Optional<String>
was coming from somewhere else. Making one just to avoid a ternary operator is questionable, but here's how you can rewrite your method:
public void methodA(String input) {
System.out.println(Optional.ofNullable(input).map(Long::valueOf).orElse(null));
}
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