Difference between OptionalInt and int?
In your first snippet, if arr
is empty, there is no maximum value. The OptionalInt
would be empty (i.e. it would contain no value).
In your second snippet, if arr
is empty, the maximum is 0
by default.
Implementing the logic of the first snippet without an OptionalInt
can be done using an Integer
variable, which can contain a null
value:
Integer maximum = null;
for (int i:arr) {
maximum = maximum != null ? Math.max(i,maximum) : i;
}
Now maximum
will remain null
if arr
is empty.
The advantage of using the stream approach over the imperative approach is that when there are no elements in the array arr
then we represent the maximum value as absent to indicate a missing value.
regarding this description you've stated:
As per the definition of OptionalInt,if value if present it returns getasIntValue() but if value is not present ,it throws Exception.
Note that it throws an exception only when you call getAsInt() directly from an optional result and the value is absent.
This is a good thing in the sense that when we attempt to access the element using getAsInt() as you've mentioned and there is no value present then a NoSuchElementException
will be thrown and in-fact getting an exception, in this case, might be useful because you now know there is no value present whereas the imperative approach could lead to hiding a bug because if the array is empty then the maximum value is 0
which is false except in a certain scenario mentioned in my 2nd to last paragraph below.
Such, small code as you've shown will probably be easy to fix when there is a bug but in production code, it may be hard to find due to the size of the codebase.
if 0
is, in fact, the default you want to provide when the array is empty then you can proceed with the imperative approach as is or using the optional approach it could be done as:
int max = IntStream.of(arr).max()
.orElse(0);
In the above scenario, the NoSuchElementException
exception will not be thrown. Also, I'd recommend not to use getAsInt() straight from an optional result unless you're 100% sure the array will not be empty. rather utilise orElse, orElseGet or orElseThrow depending on which you find most appropriate for the given situation.