Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

8 Ways of Creating a Stream Object in Java 8

DZone's Guide to

8 Ways of Creating a Stream Object in Java 8

Want to learn different ways to create a Stream object in Java 8? Check out this post where we look at eight different wats to create a Stream.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

In this article, we will discuss different ways to create a Stream object in Java 8, however, I would like to share eight different ways to create a Stream object in Java 8.

There are many ways to create a stream instance of different sources, such as Collections, Arrays, File, etc. Once created, the instance will not modify its source, therefore, allowing the creation of multiple instances from a single source.

If you are new to the Java 8 Stream API, then you should check out our article on Java 8 Stream API.

Image title

1. Empty Stream

The empty() method should be used in case of a creation of an empty stream:

Stream<String> stream = Stream.empty();
stream.forEach(System.out::println);


It's often the case that the  empty() method is used upon creation to avoid returning null for streams with no element:

public Stream<String> streamOf(List<String> list) {
    return list == null || list.isEmpty() ? Stream.empty() : list.stream();
}


2. From Collections

A Stream object can be created with 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);
    }
}


Output:

JAVA
J2EE
Spring
Hibernate
JAVA
J2EE
Spring
Hibernate
JAVA
Hibernate
J2EE
Spring


3. From Arrays

Array is a source of a Stream or Array that can be created from an existing Array or 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);
    }
}


Output:

a
b
c
a
b
c
b
c


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:

Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
streamBuilder.forEach(System.out::println);


Output:

a
b
c


5. From Stream.generate()

Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
streamGenerated.forEach(System.out::println);


Output:

element
element
element
element
element


6. From Stream.iterate()

Stream<Integer> streamIterated = Stream.iterate(1, n -> n + 2).limit(5);
streamIterated.forEach(System.out::println);


Output:

1
3
5
7
9


7. Stream of File

The Java NIO class, Files, allows us to generate a Stream of a text file through the lines() method. Every line of the text becomes an element of the stream:

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class StreamCreationExamples {
    public static void main(String[] args) throws IOException {

        Path path = Paths.get("C:\\file.txt");
        Stream<String> streamOfStrings = Files.lines(path);
        Stream<String> streamWithCharset = Files.lines(path, Charset.forName("UTF-8"));
        streamOfStrings.forEach(System.out::println);
        streamWithCharset.forEach(System.out::println);
        streamOfStrings.close();
        streamWithCharset.close();
    }
}


8. Stream of Primitives

Since 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 that allows for increased productivity:

import java.io.IOException;
import java.util.Random;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

public class StreamCreationExamples {
    public static void main(String[] args) throws IOException {
       IntStream intStream = IntStream.range(1, 3);
       intStream.forEach(System.out::println);

       LongStream longStream = LongStream.rangeClosed(1, 3);
       longStream.forEach(System.out::println);

       Random random = new Random();
       DoubleStream doubleStream = random.doubles(3);
       doubleStream.forEach(System.out::println);
   }
}


Output:

1
2
1
2
3
0.6929414814363383
0.3683384343302385
0.948888698350225


If you want to learn more about Java 8 built-in functional interfaces, check out this post: Java 8 Functional Interfaces. Additionally, you can learn more about Java 8 lambda expressions in this post: Java 8 Lambda Expressions

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

Topics:
java 8 streams ,java 8 streams example ,java 8 ,tutorial ,streams ,string

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}