Skip to content
Advertisement

Way to parseInt without try-catch in Java 8?

Is there a better way to try to convert to int a string that can be or not an integer? Integer.parseInt(String value) will work well with “25” or “019” but not with “hello” or “8A”. In Java 8, we have optional values, for example:

public static void main(String[] args) {
    Optional<Integer> optionalResult = functionThatReturnsOptionalInteger();
    Integer finalValue = optionalResult.orElse(0);
    System.out.println(finalValue);
}

public static Optional<Integer> functionThatReturnsOptionalInteger() {
    Integer[] ints = new Integer[0];
    return Stream.of(ints).findAny();
}

You do not need to check nulls, because the Optional wrapper expose useful methods to deal with this kind of situations.

But if you want to parseInt a string, that can be null, or does not contains a valid integer, the solution is the same as always:

public static Integer parseIntOrDefault(String toParse, int defaultValue) {
    try {
        return Integer.parseInt(toParse);
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

How can improve this with Java 8 features, why Integer.parseInt() has not been overloaded to return an Optional in case of bad argument? (Or just add a new method Integer.parseIntOptional() to Integer wrapper)

Advertisement

Answer

Unlike other answers that are now deleted, I don’t think this really has to do with Java being backwards-compatible.

Because an empty Optional represents a value that is absent, it would mean that the method actually worked but no results are returned.

However, parsing hello as an integer will not work and has to throw an exception, because it is an error rather than an empty result. Keep in mind that NumberFormatException extends IllegalArgumentException.

More generally speaking, Optional was made for dealing with possibly absent values (instead of using null for that), and not for error handling. Also, Optional doesn’t provide any way to know what is the error and why there is one.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement