0
0
JavaHow-ToBeginner · 3 min read

How to Create Stream in Java: Simple Guide with Examples

In Java, you create a Stream by calling stream() on a collection, using Stream.of() for values or arrays, or by using Arrays.stream(). Streams allow you to process data in a functional style with operations like filtering and mapping.
📐

Syntax

Here are common ways to create a stream in Java:

  • collection.stream(): Creates a stream from a collection like a list or set.
  • Stream.of(values): Creates a stream from given values or an array.
  • Arrays.stream(array): Creates a stream from an array.

Streams are sequences of elements supporting functional-style operations.

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

List<String> list = List.of("a", "b", "c");
Stream<String> streamFromList = list.stream();

Stream<Integer> streamOfValues = Stream.of(1, 2, 3);

int[] array = {4, 5, 6};
IntStream streamFromArray = Arrays.stream(array);
💻

Example

This example shows how to create a stream from a list and print each element.

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

public class StreamExample {
    public static void main(String[] args) {
        List<String> fruits = List.of("Apple", "Banana", "Cherry");
        Stream<String> fruitStream = fruits.stream();
        fruitStream.forEach(System.out::println);
    }
}
Output
Apple Banana Cherry
⚠️

Common Pitfalls

Common mistakes when creating streams include:

  • Trying to reuse a stream after a terminal operation (like forEach) which causes an error.
  • Confusing Stream.of() with Arrays.stream() when working with arrays.
  • Not importing java.util.stream.Stream or java.util.stream.IntStream.
java
import java.util.List;
import java.util.stream.Stream;

public class StreamPitfall {
    public static void main(String[] args) {
        List<String> items = List.of("x", "y", "z");
        Stream<String> stream = items.stream();
        stream.forEach(System.out::println); // First use
        // stream.forEach(System.out::println); // Wrong: stream already consumed

        // Correct way: create a new stream
        items.stream().forEach(System.out::println);
    }
}
Output
x y z
📊

Quick Reference

MethodDescriptionExample
collection.stream()Creates stream from a collectionList.of(1,2).stream()
Stream.of(values)Creates stream from values or arrayStream.of(1,2,3)
Arrays.stream(array)Creates stream from an arrayArrays.stream(new int[]{1,2})

Key Takeaways

Use collection.stream() to create a stream from collections like lists or sets.
Use Stream.of() to create a stream from individual values or arrays.
Arrays.stream() is best for creating streams from primitive or object arrays.
Streams cannot be reused after a terminal operation; create a new stream instead.
Always import the correct Stream classes from java.util.stream package.