简体   繁体   中英

summaryStatistics Method of IntSummaryStatistics

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 intStream = IntStream.of();
IntSummaryStatistics stat = intStream.summaryStatistics();
System.out.println(stat);  

Output :

IntSummaryStatistics{count=0, sum=0, min=2147483647, average=0.000000, max=-2147483648}
  1. What is the point of returning these values?
  2. Should not it considered the wrong result?

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 .

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM