Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between OptionalInt and int?

Tags:

java

java-8

OptionalInt max = IntStream.of(arr).max();

Or

int maximum = 0;
for (int i : arr) {
     maximum = Math.max(i, maximum);
}

Both these methods return maximum value. What does OptionalInt make a difference? As per the definition of OptionalInt, if value is present it returns getAsInt() but if value is not present, it throws an Exception.

like image 580
Aastha Jain Avatar asked Dec 26 '17 09:12

Aastha Jain


People also ask

How do you change from OptionalInt to INT?

OptionalInt getAsInt() method in Java with examples OptionalInt help us to create an object which may or may not contain a int value. The getAsInt() method returns value If a value is present in OptionalInt object, otherwise throws NoSuchElementException. Parameters: This method accepts nothing.

How do you convert int to optional integer?

The getAsInt() method is used to get the integer value present in an OptionalInt object. If the OptionalInt object doesn't have a value, then NoSuchElementException is thrown.


1 Answers

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.

like image 76
Ousmane D. Avatar answered Oct 25 '22 08:10

Ousmane D.