简体   繁体   中英

How to calculate average in java?

I'm following a tutorial and I didn't get this part where we get the average of these numbers.
Would you please explain how are these numbers calculated and how do we get 7.5 as result ?

//   Finding the average of the numbers squared

    Arrays.stream(new int[] {1,2,3,4}).map(n -> n * n).average().ifPresent(System.out::println);

result -> 7.5

Find below the breakdown of what that stream is doing

Arrays.stream(new int[] {1,2,3,4}) //Converts int[] to IntStream
.map(n -> n * n) //Squares each element of the stream, now we have 1, 4, 9, 16
.average() // Calculate average between those numbers, it's 7.5
.ifPresent(System.out::println); //We have an Optional<Double>, if it's present we print it.

So this solution is good for you, just have to get rid of .map(n -> n * n) to calculate the average of the numbers and not their square.

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