4

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
}   }
3
  • 2
    why do you want to use optional? I dont see any use for your case Commented Dec 13, 2016 at 3:47
  • 4
    That's not really what Optional is for. And you don't want to be catching NPE. Just use the tertiary although a better design is to say the contract simply does not allow null - then throwing the NPE is what is supposed to happen and happens automatically and your code is much simpler. Commented Dec 13, 2016 at 3:48
  • 2
    Isn't it ternary? :-) IMO there is no need to use Optional in your case. Something like input != null ? Long.valueOf(input) : null seems ok. What @pvg says is also reasonable. Commented Dec 13, 2016 at 6:14

2 Answers 2

9

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

This was helpful. It helped me to better understand the use of map with Optional. The ternary operator is better option as you mentioned for the above code snippet, but your answer will be useful for other scenarios in my project i.e. other than String to Long conversions.
0

In this case, the ternary operator is more readable.

public void methodA(String input) {
System.out.println(input == null ? null : Long.parseLong(input));

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.