Why summaryStatistics() method on an empty IntStream returns max and min value of integer as the maximum and minimum int value present in the stream?
IntStream
Since the list is empty and those methods return an actual value and not an Optional<Integer>
it assumes the full Integer range. Otherwise it would return an empty Optional<Integer>
.
See IntSummaryStatistics.getMax() and IntSummaryStatistics.getMin() docs, this exact behaviour is described there, when no values are recorded.
It is just sensible to return these in these corner cases.
I will just explain this behaviour IntSummaryStatistics.getMin()
here.
Example: Let us just say the list contains at least one entry. Whatever the integer value is for that entry, it is not going to be greater than Integer.MAX_VALUE
. So returning this value when there are no entries makes sense, to give an insight to the user.
Same goes for IntSummaryStatistics.getMax()
This behavior is documented in the Javadoc, so that's the correct behavior by definition:
int java.util.IntSummaryStatistics.getMin()
Returns the minimum value recorded, or Integer.MAX_VALUE if no values have been recorded.
Returns:
the minimum value, or Integer.MAX_VALUE if none
and
int java.util.IntSummaryStatistics.getMax()
Returns the maximum value recorded, or Integer.MIN_VALUE if no values have been recorded.
Returns:
the maximum value, or Integer.MIN_VALUE if none
As to "what's the point of returning these values", we can argue that the minimum value of an empty Stream
should be such that if the Stream
had any element, that element would be smaller than that value.
Similarly, we can argue that the maximum value of an empty Stream
should be such that if the Stream
had any element, that element would be larger than that value.
To find a minimum int
value in any array you typically initialize the default to Integer.MAX_VALUE
.
int min = Integer.MAX_VALUE;
for (int i : somearray) {
if (i < min) {
min = i;
}
}
return min;
So if there was nothing to iterate, the value of the default min
would be returned. For
max, the default max
is initialized to Integer.MIN_VALUE
.