javalambdajava-stream

How does this average number calculation using the Stream API work?


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


Solution

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