Question: Give three ways of making a Stream (or five, including the ones described in Special Topic 19.1). Data from special topic 19.1 Special Topic 19.1

Give three ways of making a Stream (or five, including the ones described in Special Topic 19.1).

Data from special topic 19.1

Special Topic 19.1 Infinite Streams You can make an infinite stream with

Special Topic 19.1 Infinite Streams You can make an infinite stream with the gene rate method. Provide a lambda expression with no arguments, and it is applied for each stream element. For example, Stream ones Stream.generate (() -> 1); is an infinite stream of ones, and Stream dieTosses = Stream.generate(() -> 1+ (int) (6 * Math.random())); is an infinite stream of random integers between 1 and 6. If you want to have more interesting infinite streams, use the iterate method. You provide an initial value and an iteration function that is applied to each preceding value. For example, Stream integers = Stream.iterate(0, n -> n + 1); is an infinite stream with elements 0, 1, 2, 3, and so on. By filtering, you can get more interesting streams. For example, if is Prime is a static method that checks whether an integer is prime, then Stream primes is a stream of prime numbers. integers.filter(n -> isPrime(n)); Of course, you cannot generate all elements for such a stream. At some point, you need to limit the results. If you want to find the first 500 primes, call List firstPrimes = primes .limit (500) .collect (Collectors.toList()); What is the advantage of using an infinite stream even though it eventually gets truncated to a finite one? You don't need to know in advance how many integers to use to end up with the desired number of primes. EXAMPLE CODE See your eText or companion code for a program that demonstrates an Infinite stream.

Step by Step Solution

3.29 Rating (158 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

The question asks for three ways to create a Stream in Java with the potential to list five ways including those from the provided Special Topic 191 H... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Java Programming Questions!