【发布时间】:2021-07-30 07:55:33
【问题描述】:
我正在学习一个教程,但我没有得到这部分我们得到这些数字的平均值。
请您解释一下这些数字是如何计算的以及我们如何得到 7.5 作为结果?
// Finding the average of the numbers squared
Arrays.stream(new int[] {1,2,3,4}).map(n -> n * n).average().ifPresent(System.out::println);
结果-> 7.5
【问题讨论】:
-
请注意,它是每个值的平方的平均值,因为它正在执行
.map(n -> n * n)。map()返回{1,4,9,16}并且这些值的平均值是 7.5 -
您正在对数字进行平方,然后计算平方和的平均值。只需删除 map 语句,它就会起作用。
Arrays.stream(new int[] { 1, 2, 3, 4 }).average() -
你得到了什么?
-
@JustAnotherDeveloper 谢谢。我现在得到了答案。