Java 8 Optional Null Check

I am trying to check if the input is null, then the output should be null Or, if the input is String, then it should convert it to Long

Assuming the input is never "abcd", the input is null or "12", "14", etc.

The following code fragment throws a null pointer exception because I cannot use Java 8 correctly. Can I catch a null pointer exception or use if / else with a tertiary '?' operator, but is there any way to handle this scenario with an option?

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
}   }
+4
source share
1 answer

map Optional<String> Optional<Long>:

Optional<String> str = ...;
Optional<Long> num = str.map(Long::valueOf);

str , num . str , num valueOf. , Optional<String> - . , , , :

public void methodA(String input) {
    System.out.println(Optional.ofNullable(input).map(Long::valueOf).orElse(null));
}
+9

Source: https://habr.com/ru/post/1663579/


All Articles