Java Reference
In-Depth Information
Generating tuples
Following the filter, you know that both a and b can form a correct combination. You now need
to create a triple. You can use the map operation to transform each element into a Pythagorean
triple as follows:
stream.filter(b -> Math.sqrt(a*a + b*b) % 1 == 0)
.map(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)});
Generating b values
You're getting closer! You now need to generate values for b. You saw that Stream .rangeClosed
allows you to generate a stream of numbers in a given interval. You can use it to provide
numeric values for b, here 1 to 100:
IntStream.rangeClosed(1, 100)
.filter(b -> Math.sqrt(a*a + b*b) % 1 == 0)
.boxed()
.map(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)});
Note that you call boxed after the filter to generate a Stream<Integer> from the IntStream
returned by rangeClosed. This is because your map returns an array of int for each element of
the stream. The map method from an IntStream expects only another int to be returned for each
element of the stream, which isn't what you want! You can rewrite this using the method
mapToObj of an IntStream, which returns an object-valued stream:
IntStream.rangeClosed(1, 100)
.filter(b -> Math.sqrt(a*a + b*b) % 1 == 0)
.mapToObj (b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)});
Generating a values
There's one crucial piece that we assumed was given: the value for a. You now have a stream that
produces Pythagorean triples provided the value a is known. How can you fix this? Just like with
b, you need to generate numeric values for a! The final solution is as follows:
Stream<int[]> pythagoreanTriples =
IntStream.rangeClosed(1, 100).boxed()
.flatMap(a ->
 
Search WWH ::




Custom Search