Way to parseInt without try-catch in Java 8?

Viewed 11805

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)

6 Answers

Google's Guava library provides a helper method to do this: Ints.tryParse(String).It runs null when the string is not parsable. You can checkout the documentation.

Using Mutiny it can be written like this.

If you just want to do something with the result you could do it in a single expression

Uni.createFrom()
  .item(() -> Integer.parseInt(toParse))
  .onFailure().recoverWithItem(defaultValue)
  .subscribe().with(i -> System.out.println(i));

Or create a method like the one intended

    public static Integer parseIntOrDefault(String toParse, int defaultValue) {
        Integer[] toReturn = new Integer[]{null};
        Uni.createFrom()
           .item(() -> Integer.parseInt(toParse))
           .onFailure().recoverWithItem(defaultValue)
           .subscribe().with(i -> toReturn[0] = i);
        return toReturn[0];
}

This solution adds a library, but the lib is not specific to handle this problem. It uses reactive programing, futures, callbacks and a fluent API and proves to be flexible enough to solve this problem.

Related