8 Ways of Creating A Stream in Java 8
8 Ways of Creating A Stream in Java 8
1. Empty Stream
2. From Collections
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
stream2.forEach(System.out::println);
stream3.forEach(System.out::println);
stream4.forEach(System.out::println);
}
3. From Arrays
Array can be a source of a Stream or Array can be created from existing array or of a part of an
array:
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Stream;
streamOfArray.forEach(System.out::println);
streamOfArrayFull.forEach(System.out::println);
4. From Stream.builder()
When a builder is used the desired type should be additionally specified in the right part of the
statement, otherwise, the build() method will create an instance of the Stream:
5. From Stream.generate()
6. From Stream.iterate()
Stream of Primitives
As Stream is a generic interface and there is no way to use primitives as a type parameter with
generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
Using the new interfaces alleviates unnecessary auto-boxing allows increased productivity: