The Streams
are the flow of data, Streams
can be finite
and infinite
. Finite
streams can be generated in multiple ways such as List
, Map
etc which we have already seen before.
Java 8 provides functions to generate infinite
streams as well, it will keep on providing new elements unless not stopped or a limit
is applied.
Generate
Generate
functions defined in Stream
class takes a Supplier
function which will generate the next element of Infinite
Stream.
package org.wesome.java8;
import java.util.Random;
import java.util.stream.Stream;
class Apple {
public static void main(String args[]) {
/*---------------Math random---------------*/
Stream.generate(Math::random).limit(5).forEach(System.out::println);
/*---------------Random---------------*/
Stream.generate(Random::new).map(Random::nextInt).limit(5).forEach(System.out::println);
}
}
Iterate
The Iterate
method takes 2 parameters, seed
which is the initial value
of the infinite
stream, and a Unary operator
, which will take a single input, process it and return the single output.
package org.wesome.java8;
import java.util.stream.Stream;
class Apple {
public static void main(String args[]) {
/*-------------------------iterate-------------------------*/
Stream.iterate(1, i -> i + 1).limit(5).forEach(System.out::println);
}
}
Infinite streams
are majorly used where the end is not fixed or bound. for example, find the first 10
elements which are divisible by 2,3,4 and 5
package org.wesome.java8;
import java.util.stream.IntStream;
public class Apple {
public static void main(String[] args) {
int limit = 10;
IntStream.iterate(1, value -> value + 1)
.filter(value -> value % 2 == 0)
.filter(value -> value % 3 == 0)
.filter(value -> value % 4 == 0)
.filter(value -> value % 5 == 0)
.limit(limit)
.forEach(System.out::println);
}
}