java8 - 可选- 如何正确使用?

java8 - Optional- How to use it correctly?

cityStr 是一个字符串,它可以是 null 或“”。我想把它变成一个 int,如果它大于 0,那么我将打印 "the city is exist".

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

我想用下面的代码来代替上面的代码,但是出现了异常。我怎样才能正确使用它?非常感谢您的回答。

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

下面是异常信息:

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)

您正在尝试从空字符串中解析数字。那会抛出异常。与Optional无关。

也许您认为空字符串应该是 'nullish' - 就像 javascript 中的空字符串是假的。

要消除异常,请将 null 或数字分配给 cityStr

你可以这样写:

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

如果您需要非数字字符串,则必须在 map 方法中自行处理。

根据@fastcodejava的建议,我对程序做了一些小改动,请看下面:

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;
        }
    }

其中 MainClass 是主要方法 class MainClass.java