Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Optional Null Check

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
}   }
like image 367
David Avatar asked Jan 04 '23 22:01

David


1 Answers

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));
}
like image 67
Misha Avatar answered Jan 07 '23 17:01

Misha