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)