Exercises: Streams Part 3
1. Make a very large array of random doubles, each of which ranges from 0 to 1. A quick and easy
way to do this is with “new Random().doubles(size).toArray()”.
2. Compute the sum of the square roots of the numbers in the array. Find a shorter and simpler way
than making a loop to tally the sum. Hint: review the notes on number-specialized streams, espe-
cially the fact that you make a DoubleStream from a double[] with [Link], not [Link].
3. Repeat the process in parallel. Once you have #2 working, this should be very simple.
4. Verify that you get the “same” answer with the parallel approach as with the sequential approach.
Why do I have “same” in quotes in the previous sentence?
5. Test whether the parallel approach is faster than the sequential approach. Doing the timing is a little
bit tedious, but if you think it simplifies things, you can steal the Op interface from streams-3-exer-
cises project, then do something like this:
[Link](() -> {
double sum = [Link](nums);
[Link](" Sum is %,.8f.%n", sum);
});
6. Make an “infinite” stream that generates random doubles between 0 and 10. Use it to
• Print 5 random doubles
• Make a List of 10 random doubles
• Make an array of 20 random doubles
Note on printing arrays: in previous exercises, you printed an array by doing
[Link]([Link](yourArray));
This trick only works for arrays of objects, so it does not work if you have a double[], only if you
have a Double[]. If you used [Link], no problem: you have a Stream<Double>, and from
that you can use toArray(Double[]::new) to get a Double[], then use the above trick to print the
array. However, if you used [Link], you have a DoubleStream (which is not the
same as a Stream<Double>). Given a DoubleStream, you can use toArray() to get a double[], but
then you cannot use the above trick to print the array. Either approach ([Link] or Dou-
[Link]) is fine, and perhaps [Link] is slightly preferred here. But, if
you use [Link] and later produce an array, you will have to print out the elements
with a loop of some sort.
Customized Java EE training at your location: JSF 2, PrimeFaces, Hadoop, general Java programming, Java 8 lambdas/streams, JavaScript, jQuery, Android, Spring MVC, GWT, REST, etc.
For sample tutorials and public courses, see [Link] To inquire about onsite courses, email hall@[Link].