Skip to content

Different Ways To Create Stream Objects

In this lesson, you will learn how to create streams in different ways with practical examples.

Gopi Gorantala
Gopi Gorantala
5 min read

Table of Contents

In Java, there are several ways to create streams depending on the source of data. Here are some common ways to create streams:

  1. Empty stream
  2. Stream from a collection.
  3. Stream from an array.
  4. Stream from static factory methods.
  5. Stream from I/O operations.
  6. Stream from other sources.

Empty stream

The empty() method is used to create an empty stream.

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

We generally do the following to avoid returning null for streams with no element. An example is shown below:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamEmptyCreation {
  public static void main(String[] args) {
    // not empty collection items
    System.out.println("Non empty collections");
    List<String> languages = Arrays.asList("English", "Spanish", "French", "Hindi");
    isEmptyStream(languages).forEach(System.out::println);

    // for empty collections
    System.out.println("Empty collections");
    List<String> emptyLocales = new ArrayList<>();
    isEmptyStream(emptyLocales).forEach(System.out::println); // prints nothing
  }

  // this is how we check and give empty stream.
  public static Stream<String> isEmptyStream(List<String> languages) {
    return languages == null || languages.isEmpty() ? Stream.empty() : languages.stream();
  }
}

The above code prints the following on the console.

/*
Non empty collections
English
Spanish
French
Hindi
Empty collections
*/

Stream from a Collection

You can create a stream from a collection using the stream() method provided by the Collection interface. For example:

package src.dev.ggorantala.course.chapters.streams.intro.createstreams;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamCollection {
  public static void main(String[] args) {
    List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

    Stream<String> stream = names.stream();

    // Perform operations on the stream
    stream.forEach(System.out::println);
  }
}

The above code prints the following on the console.

/*
Alice
Bob
Charlie
*/

In the above example, we have a list of names, and we create a stream from it using the stream() method. The stream() method returns a sequential stream that allows us to perform various operations on the elements of the collection.

Once the stream is created, we can apply operations like filtering, mapping, sorting, and more to process the elements in a declarative and functional manner.

In the example, we simply call the forEach() method on the stream to print each element. The forEach() method is a terminal operation that consumes each element of the stream and performs the specified action.

Note that after the terminal operation is performed on the stream, the stream is considered consumed and cannot be reused. If you need to perform multiple operations on the same collection, you can create a new stream from the collection each time.

Stream from an Array

To create a stream from an array in Java, you can use the stream() method provided by the Arrays class. Here's an example:

package src.dev.ggorantala.course.chapters.streams.intro.createstreams;

import java.util.Arrays;
import java.util.stream.Stream;

public class ArrayStream {
  public static void main(String[] args) {
    String[] names = {"Alice", "Bob", "Charlie"};

    Stream<String> stream = Arrays.stream(names);

    // Perform operations on the stream
    stream.forEach(System.out::println);
  }
}

The above code prints the following on the console.

/*
Alice
Bob
Charlie
*/

In the above example, we have an array of names, and we create a stream from it using the Arrays.stream() method. The stream() method returns a sequential stream that allows us to perform various operations on the elements of the array.

Once the stream is created, we can apply operations like filtering, mapping, sorting, and more to process the elements in a declarative and functional manner.

In the example, we simply call the forEach() method on the stream to print each element. The forEach() method is a terminal operation that consumes each element of the stream and performs the specified action.

Note that after the terminal operation is performed on the stream, the stream is considered consumed and cannot be reused. If you need to perform multiple operations on the same array, you can create a new stream from the array each time.

Stream from static factory methods

The static factory methods include:

  1. Stream.of
  2. Stream.iterate
  3. Stream.generate

In Java, the Stream interface provides static factory methods that allow you to create streams directly. These methods provide a convenient way to create streams without explicitly working with collections or arrays.

Here are some examples of static factory methods to create streams:

Stream.of

Creating a stream of individual elements using Stream.of():

package src.dev.ggorantala.course.chapters.streams.intro.createstreams;

import java.util.stream.Stream;

public class StreamOfExample {
  public static void main(String[] args) {
    Stream<Integer> stream1 = Stream.of(1, 2, 3);
    stream1.forEach(System.out::println);

    Stream<String> stream2 = Stream.of("apple", "banana", "orange");
    stream2.forEach(System.out::println);
  }
}

The above code prints the following on the console.

/*
1
2
3
apple
banana
orange
*/

In the above example, we create a stream of integers and a stream of strings using the Stream.of() method. The method takes a variable number of arguments, and each argument represents an element in the resulting stream.

Stream.iterate

Generating a stream using Stream.iterate():

package src.dev.ggorantala.course.chapters.streams.intro.createstreams;

import java.util.stream.Stream;

public class StreamIterateExample {

  public static void main(String[] args) {
    Stream<Integer> stream = 
            Stream.iterate(0, n -> n + 2)
                .limit(3);
    stream.forEach(System.out::println);
  }
}

The above code prints the following on the console.

/*
0
2
4
*/

In the above example, we create a stream of even numbers using the Stream.iterate() method. The method takes an initial value and a function that generates the next value based on the previous value. In this case, we start from 0 and generate the next even number by adding 2 each time. We also use the limit() method to restrict the stream to a certain number of elements.

Stream.generate

Generating a stream using Stream.generate():

package src.dev.ggorantala.course.chapters.streams.intro.createstreams;

import java.util.stream.Stream;

public class StreamGenerateExample {
  public static void main(String[] args) {
    Stream<Integer> stream =
            Stream.generate(() -> 42)
                    .limit(3);
    stream.forEach(System.out::println);
  }
}

The above code prints the following on the console.

/*
42
42
42
*/

In the above example, we create a stream of constant values using the Stream.generate() method. The method takes a supplier that produces the desired value, in this case, 42. We also use the limit() method to restrict the stream to a certain number of elements.

These static factory methods provide flexibility and convenience when creating streams directly from specific elements or using custom functions. Once the stream is created, you can apply various stream operations to process the data.

Stream from I/O operations

You can create a stream from I/O operations, such as reading lines from a file, using the lines() method provided by the BufferedReader class.

For example:

Path filePath = Paths.get("file.txt");
BufferedReader reader = Files.newBufferedReader(filePath);
Stream<String> lines = reader.lines();

Stream from other sources:

Java also provides methods to create streams from other sources, such as IntStream, LongStream, and DoubleStream for primitive types.

Additionally, you can create streams from regular expressions, ranges, and more.

package src.dev.ggorantala.course.chapters.streams.intro.createstreams;

import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

public class OtherStreams {
  public static void main(String[] args) {
    IntStream.range(1, 4).forEach(System.out::println);

    LongStream.range(6, 9).forEach(System.out::println);

    new Random().doubles(2).forEach(System.out::println);
  }
}

The above code prints the following on the console:

/*
1
2
3
6
7
8
0.7467801106967968
0.2932841273128075
*/

These are some of the common ways to create streams in Java. Once you have a stream, you can apply various operations such as filtering, mapping, reducing, and more to process the data in a declarative and functional way.

Java Streams APIJava

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Differences Between JDK, JRE, and JVM?

Short answer JDK, JRE, and JVM are essential components of the Java platform, each serving a distinct purpose. Here are the key differences between them: 1. JDK (Java Development Kit): The JDK is used by developers to write, compile, and debug Java code. 2. JRE (Java Runtime Environment): End-users use

Members Public

Difference Between String and char[] in Java

Short answer Strings String is an object with many helpful methods. String class in Java's standard library is designed to handle text as a sequence of characters. A string of characters (string object) is non-modifiable or immutable in Java. Once you've created it, you cannot modify

Members Public

What is an Object class in Java?

Short answer Object class is the super class of every class you can create. In Java, a class extends another class using the keyword extends. If you don't have any other class to extend, that's fine. The compiler will make your class extend the Object class.