Question: Used map and sum to calculate the sum of the squares of an IntStreams values. Reimplement stream pipeline in Fig. 17.9 to replace map and
Used map and sum to calculate the sum of the squares of an IntStream’s values. Reimplement stream pipeline in Fig. 17.9 to replace map and sum with the following reduce, which receives a lambda that does not represent an associative operation:
.reduce((x, y) -> x + y * y)
Error-Prevention Tip 17.2 cautioned you that reduce’s argument must be an associative operation. Execute the reimplemented stream pipeline using a parallel stream. Does it produce the correct sum of the squares of the IntStream’s values?
Fig. 17.9 
I // Fig. 17.9: IntStreamOperations.java // Demonstrating IntStream operations. 3 import java.util.Arrays; 4 import java.util.stream.Collectors; 5 import java.util.stream. IntStream; 11 13 14 15 16 17 18 19 26 27 28 29 33 35 36 38 39 40 41 42 43 44 48 49 public class IntStreamOperations { public static void main(String[] args) { int[] values = {3, 10, 6, 1, 4, 8, 2, 5, 9, 7}; 50 51 } } // display original values System.out.print("Original values: "); System.out.println( IntStream. of (values) .mapToobj (String::value0f) .collect(Collectors.joining (" "))); // count, min, max, sum and average of the values System.out.printf("%nCount: %d %n", IntStream.of (values) .count(()); System.out.printf("Min: %d %n", IntStream.of (values).min().getAsInt()); System.out.printf("Max: %d%n", IntStream.of (values).max().getAsInt()); System.out.printf("Sum: %d %n", IntStream.of (values). sum()); System.out.printf("Average: %.2f%n", IntStream.of (values).average().getAsDouble()); // sum of values with reduce method System.out.printf("%nSum via reduce method: %d%n", IntStream.of (values) .reduce(0, (x, y) -> x + y)); // product of values with reduce method System.out.printf("Product via reduce method: %d%n", IntStream. of (values) .reduce ((x, y) -> x* y).getAsInt ()); // sum of squares of values with map and sum methods System.out.printf("Sum of squares via map and sum: %d%n%n", IntStream.of (values) .map(x-> x* x) .sum()); // displaying the elements in sorted order System.out.printf("Values displayed in sorted order: %s%n", IntStream.of (values) . sorted () .mapToobj (String: :value0f) .collect (Collectors.joining (" "))); Original values: 3 10 6 1 4 8 2597 Count: 10 Min: 1 Max: 10 Sum: 55 Average: 5.50 Sum via reduce method: 55 Product via reduce method: 3628800 Sum of squares via map and sum: 385 Values displayed in sorted order: 1 2 3 4 5 6 7 8 9 10
Step by Step Solution
3.45 Rating (152 Votes )
There are 3 Steps involved in it
In the presented Java code from Figure 179 there is a segment that calculates the sum of the squares ... View full answer
Get step-by-step solutions from verified subject matter experts
