Streams

Stream Creation

A Stream is always created from a data source. Every pipeline starts here.

Ways to Create a Stream

SourceCode
Collectionlist.stream()
ArrayArrays.stream(arr)
Explicit valuesStream.of(1, 2, 3)
BuilderStream.builder().add(1).add(2).build()
Iterate (infinite)Stream.iterate(seed, fn)
Generate (infinite)Stream.generate(supplier)
Range of intsIntStream.range(1, 5), rangeClosed(1, 5)

1. From a Collection

Every Collection (List, Set, Queue) has a stream() method.

List<Integer> numbers = List.of(1, 2, 3, 4, 5);
Stream<Integer> stream = numbers.stream();

A Map has no stream() method. Stream its keySet(), values(), or entrySet() instead.

Map<Integer, String> map = Map.of(1, "Ravi", 2, "Anita");
map.keySet().stream();
map.values().stream();
map.entrySet().stream();

2. From an Array

int[] numbers = {1, 2, 3, 4, 5};
IntStream s1 = Arrays.stream(numbers); // primitive array gives IntStream
String[] names = {"Akash", "Rahul", "Amit"};
Stream<String> s2 = Arrays.stream(names); // object array gives Stream<String>

3. Using Stream.of()

Creates a Stream from explicitly provided values.

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);

4. Using Stream.Builder

Stream.Builder<Integer> builder = Stream.builder();
builder.add(1);
builder.add(2);
builder.add(3);
Stream<Integer> stream = builder.build();

5. Using Stream.iterate()

Generates a sequence from a starting value and a function that produces the next value.

// With limit
Stream.iterate(1000, n -> n + 5000)
.limit(5)
.forEach(System.out::println);
// 1000, 6000, 11000, 16000, 21000
// With a stop condition (Java 9+)
Stream.iterate(1, n -> n <= 20, n -> n * 2)
.forEach(System.out::println);
// 1, 2, 4, 8, 16

6. Using Stream.generate()

Produces elements from a Supplier.

Stream.generate(() -> "Hello")
.limit(3)
.forEach(System.out::println);
// Hello, Hello, Hello
Stream.generate(Math::random)
.limit(3)
.forEach(System.out::println);

iterate() and generate() can produce an infinite Stream. Always restrict them with limit() or a stop condition.

7. Ranges of Numbers

IntStream.range(1, 5).forEach(System.out::println); // 1 2 3 4 (end excluded)
IntStream.rangeClosed(1, 5).forEach(System.out::println); // 1 2 3 4 5 (end included)

8. Other Sources

SourceCode
String characters"hello".chars()
Empty StreamStream.empty()
Files (lines)Files.lines(path)
Regex splitPattern.compile(",").splitAsStream(s)

Remember

Collections use .stream(), arrays use Arrays.stream(), values use Stream.of(), and infinite sequences use iterate() or generate() with limit().