8 Ways of Creating a Stream in Java 8
1. Empty Stream
The empty() method should be used in case of a creation of an empty stream:
2. From Collections
Stream can be created of any type of Collection (Collection, List, Set):
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;
public class StreamCreationExamples {
public static void main(String[] args) throws IOException {
Collection<String> collection = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");
Stream<String> stream2 = collection.stream();
stream2.forEach(System.out::println);
List<String> list = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");
Stream<String> stream3 = list.stream();
stream3.forEach(System.out::println);
Set<String> set = new HashSet<>(list);
Stream<String> stream4 = set.stream();
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;
public class StreamCreationExamples {
public static void main(String[] args) throws IOException {
// Array can also be a source of a Stream
Stream<String> streamOfArray = Stream.of("a", "b", "c");
streamOfArray.forEach(System.out::println);
// creating from existing array or of a part of an array:
String[] arr = new String[] { "a", "b", "c" };
Stream<String> streamOfArrayFull = Arrays.stream(arr);
streamOfArrayFull.forEach(System.out::println);
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
streamOfArrayPart.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: