简体   繁体   中英

java8 - Optional- How to use it correctly?

The cityStr is a String, and it would be a null or "". I want to turn it to a int and if it's greater than 0, then I will print "the city is exist".

 if (StringUtils.isNotBlank(cityStr)) {
        if (Integer.parseInt(cityStr) > 0) {
            System.out.println("the city is exist");
        }
 }

I want to used the below code to replace the above code, but I got a exception. How can I use it correctly? Thanks so much for your answer.

    if (Optional.ofNullable(cityStr)
            .map(Integer::parseInt)
            .filter(city -> city > 0)
            .isPresent()) {
        System.out.println("the city is exist");
    }

And the below is the exception information:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at java.util.Optional.map(Optional.java:215)

You are trying to parse a number from an empty String. That throws the exception. It has nothing to do with Optional.

Maybe you thought that an empty string would be 'nullish' - like an empty String being falsy in javascript.

To get rid of the exception, assign null or a number to cityStr .

You could write it as:

String cityStr = null;
if (Optional.ofNullable(cityStr)
        .map(Integer::parseInt)
        .filter(city -> city > 0)
        .isPresent()) {
    System.out.println("the city is exist");
}

If you are expecting non numeric string you've to handle that yourself in the map method.

As suggested by @fastcodejava I made minor changes to the program, please take a look below:

public static void main(String[] args) throws NoSuchAlgorithmException {
        String cityStr = "1";

        Optional<String> cityOptional = Optional.ofNullable(cityStr)
                .map(MainClass::parseInt)
                .filter(integer -> integer > 0)
                .map(integer -> "city exists");

        String cityString = cityOptional.orElse("city does not exists");
        System.out.println(cityString);


    }

    public static int parseInt(String str) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            // Eating e for unknown reason
            return -1;
        }
    }

Where MainClass is the class for main method MainClass.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM