Java Reference
In-Depth Information
Here you use the rangeClosed method to generate a range of all numbers from 1 to 100. It
produces a stream so you can chain the filter method to select only even numbers. At this stage
no computation has been done. Finally, you call count on the resulting stream. Because count is
a terminal operation, it will process the stream and return the result 50, which is the number of
even numbers from 1 to 100, inclusive. Note that by comparison, if you were using
IntStream.range(1, 100) instead, the result would be 49 even numbers because range is
exclusive.
5.6.3. Putting numerical streams into practice: Pythagorean triples
We now look at a more difficult example so you can solidify what you've learned about numeric
streams and all the stream operations you've learned so far. Your mission, if you choose to
accept it, is to create a stream of Pythagorean triples.
Pythagorean triple
So what's a Pythagorean triple? We have to go back a few years in the past. In one of your
exciting math classes, you learned that the famous Greek mathematician Pythagoras discovered
that certain triples of numbers (a, b, c) satisfy the formula a * a + b * b = c * c where a, b, and c
are integers. For example, (3, 4, 5) is a valid Pythagorean triple because 3 * 3 + 4 * 4 = 5 * 5 or 9
+ 16 = 25. There are an infinite number of such triples. For example, (5, 12, 13), (6, 8, 10), and (7,
24, 25) are all valid Pythagorean triples. Such triples are useful because they describe the three
side lengths of a right-angled triangle, as illustrated in figure 5.9 .
 
Search WWH ::




Custom Search