summaryStatistics Method of IntSummaryStatistics

╄→гoц情女王★ 提交于 2020-07-16 06:41:43

问题


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?

回答1:


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()




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/58913936/summarystatistics-method-of-intsummarystatistics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!