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: 66% (3 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...
-
International Dairy Queen, Inc., a firm whose business is highly seasonal, has reported the following quarterly net income figures for 1991 through 1995. a. Construct the four-quarter centered moving...
-
Gilead is a large drug producer, with a majority of its prescription drug product sales occurring in the United States. Gilead produces anti-HIV drug therapies, including the drugs Atripla, Truvada,...
-
Fair Value Addison Manufacturing holds a large portfolio of debt and equity securities as an investment. The fair value of the portfolio is greater than its original cost, even though some securities...
-
Describe the economic impact on healthcare. Elaborate on how consumers and businesses were impacted and evaluate the outcomes for the entire industry. Explain with at least three hundred words
-
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...
-
What are six incentive compensation plans?
-
"Coming Soon: A Theater Near You" Case Questions Read the case "Coming Soon: A Theater Near You" (HBS 9-797-011). Then consider the following questions: 1. Are the trading relationships between the...
-
Direct quote for a Malaysian investor for Singapore dollars is RM3.06/S$. Hence, the indirect quote for the Malaysian investor would be quote for the Singaporean investor would be A) RM0.327/S$;...
-
When cooking frozen cheese ravioli, the directions say to putthe 255 grams of filled pasta into 3 quarts of boiling water. Whyshould you use 3 quarts when 1 quart would easily cover them all?Suppose...
-
You borrow $330,000 through a 30-year fixed-rate mortgage at an interest rate of 2.5% and a monthly payment of $1,303.90. You observe that 6 years after taking out the mortgage, mortgage rates fall...
-
You are considering opening a new plant. The plant will cost $96.4 million upfront. It expected to produce profits of $28.7 million at the end of every year, starting year 1. The cash flows are...
-
Using the Web site edgarscan.pwcglobal.com/servlets/edgarscan, enter Hershey Foods. Click on Hershey Foods Corp. and then click on 10-K 20041231. Fetch the entire 10-K filing by clicking on text rich...
-
How can NAFTA be beneficial to suppliers of Walmart?
-
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...
-
The following five dice are pictured here: tetrahedron (4 faces and yellow), cube (6 faces and pink), octahedron (8 faces and green), dodecahedron (12 faces and yellow), icosahedron (20 faces and...
-
Show that f'() and f"(2) exists everywhere at any point: and find f'(2) and f"() if (a) f (z) = iz +2, (b) f(z)= a*, (c) f(z)=cosr coshy isin 2 sinh y.
-
What class of laws did local governments pass to empower police departments to regulate groups' right to be in public life?
Study smarter with the SolutionInn App