Used map and sum to calculate the sum of the squares of an IntStreams values. Reimplement stream
Question:
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
Transcribed Image Text:
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
Fantastic news! We've Found the answer you've been seeking!
Step by Step Answer:
Answer rating: 50% (4 reviews)
In the presented Java code from Figure 179 there is a segment that calculates the sum of the squares ...View the full answer
Answered By
Asim farooq
I have done MS finance and expertise in the field of Accounting, finance, cost accounting, security analysis and portfolio management and management, MS office is at my fingertips, I want my client to take advantage of my practical knowledge. I have been mentoring my client on a freelancer website from last two years, Currently I am working in Telecom company as a financial analyst and before that working as an accountant with Pepsi for one year. I also join a nonprofit organization as a finance assistant to my job duties are making payment to client after tax calculation, I have started my professional career from teaching I was teaching to a master's level student for two years in the evening.
My Expert Service
Financial accounting, Financial management, Cost accounting, Human resource management, Business communication and report writing. Financial accounting : • Journal entries • Financial statements including balance sheet, Profit & Loss account, Cash flow statement • Adjustment entries • Ratio analysis • Accounting concepts • Single entry accounting • Double entry accounting • Bills of exchange • Bank reconciliation statements Cost accounting : • Budgeting • Job order costing • Process costing • Cost of goods sold Financial management : • Capital budgeting • Net Present Value (NPV) • Internal Rate of Return (IRR) • Payback period • Discounted cash flows • Financial analysis • Capital assets pricing model • Simple interest, Compound interest & annuities
4.40+
65+ Reviews
86+ Question Solved
Related Book For
Java How To Program Late Objects Version
ISBN: 9780136123712
8th Edition
Authors: Paul Deitel, Deitel & Associates
Question Posted:
Students also viewed these Computer science questions
-
Calculate the moment of inertia of a thin plate, in the shape of a right triangle, about an axis that passes through one end of the hypotenuse and is parallel to the opposite leg of the triangle, as...
-
Required a. Use professional judgment in deciding on the preliminary judgment about materiality for earnings, current assets, current liabilities, and total assets. Your conclusions should be stated...
-
The most fundamental managerial accounting tool is a cost benefit analysis. For this question, do Cost Benefit Analysis of the budgeting process. Creating a budget is very costly in terms of the...
-
In Exercises 1138, use the given conditions to write an equation for each line in point-slope form and slope-intercept form. Slope = 2, passing through (3, 5)
-
The rotational spectrum of HC1 contains the following wavelengths (among others): 60.4m, 69.0m, 80.4m, 96.4m, and 120.4m. Use this spectrum to find the moment of inertia of the HCI molecule about an...
-
Historically, Shop-Mart has gotten an average of 2000 hours of use from its G&E fluorescent lightbulbs. Because its fixtures are attached to the ceiling, the bulbs are rather cumbersome to replace,...
-
Under what circumstances might a salary or bonus be more appropriate than interest on capital balances as a means of allocating profits? AppendixLO1
-
A General Power bond carries a coupon rate of 8%, has 9 years until maturity, and sells at a yield to maturity of 7%. (Assume annual interest payments.) a. What interest payments to bondholders...
-
The security market line is defined as a positively sloped straight line that displays the relationship between the: risk premium and beta of a portfolio. beta and standard deviation of a portfolio....
-
Demonstrated the recursive merge sort algorithm. Reimplement the program of Fig. 19.6 using the Fork/Join Framework. Fig. 19.6 I // Fig. 19.6: MergeSortTest.java // Sorting an array with merge sort....
-
In Fig. 17.24 , we implemented a stream pipeline that rolled a die 60,000,000 times using values produced by SecureRandom method ints. Use the same timing techniques you used in Exercise 17.25 to...
-
The eyepiece of a compound microscope has a focal length of 2.70 cm, and the objective lens has f =0.740 cm, if an object is placed 0.790 cm from the objective lens, calculate (a) The distance...
-
Prove that Eq. (19.34) gives the simplest multi-gluon and gluon-quark states that contain an \(\mathrm{SU}(3)\) color singlet in the decomposition. Data from Eq. 19.34 (GG)1: (88)1 (Gqq) : [8 (383)8]...
-
In question 70, what is the probability that of the 100 cars test-driven, more than 35 cars get more than 45 miles per gallon? How many of the 100 cars tested would you expect to get more than 45...
-
Construct the braid group products (a) (b) using the algorithm of Fig. 29.16 . Data from Fig. 29.16
-
Worksheet The adjusted trial balance columns of a worksheet for Bond Corporation are shown below. The worksheet is prepared for the year ended December 31. Complete the worksheet by (a) entering the...
-
The Healthy Catering Service had the following transactions in July, its first month of operations: 1 Kelly Foster contributed \(\$ 18,000\) of personal funds to the business in exchange for common...
-
In support of the Fed's monetary policy prior to the deflation of the home prices bubble, one can argue that the reality is that increasing the money supply and low-interest rates were required to...
-
Dan and Diana file a joint return. Dan earned $31,000 during the year before losing his job. Diana received Social Security benefits of $5,000. a. Determine the taxable portion of the Social Security...
-
Repeat Problem 6-4 if each output slot carries 2 bits from each source. Problem 6-4 We need to use synchronous TDM and combine 20 digital sources, each of 100 Kbps. Each output slot carries 1 bit...
-
Five equal-size datagrams belonging to the same message leave for the destination one after another. However, they travel through different paths as shown in Table 8.1. We assume that the delay for...
-
We mentioned that two types of networks, datagram and virtual-circuit, need a routing or switching table to find the output port from which the information belonging to a destination should be sent...
-
You borrowed $15,000 for buying a new car from a bank at an interest rate of 12% compounded monthly. This loan will be repaid in 48 equal monthly installments over four years. Immediately after the...
-
Discuss how debt restructuring, settlement, or modification works. Discuss the journal entries for debtor and creditor
-
Could CNL be a viable business? If so, under what conditions and what level of production (and, since production is directly related to production workers, employees)? All information provided for...
Study smarter with the SolutionInn App