Learnitweb

How to convert Array to Stream?

In Java 8, there are two methods to convert Array into a Stream:

  • Stream.toArray()
  • Arrays.stream()

1. Object Arrays

In case of object arrays, you can use both Arrays.stream() and Stream.of() methods as both return the same output.

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

public class ArrayToStreamExample {

	public static void main(String[] args) {
		String[] array = { "a", "b", "c" };

		// Using Arrays.stream()
		Stream<String> stream1 = Arrays.stream(array);

		System.out.println("Output using Arrays.stream");
		stream1.forEach(x -> System.out.println(x));

		// Using Stream.of()
		Stream<String> stream2 = Stream.of(array);

		System.out.println("Output using Stream.of");
		stream2.forEach(x -> System.out.println(x));
	}
}

Output

Output using Arrays.stream
a
b
c
Output using Stream.of
a
b
c

For object arrays, the Stream.of() method calls the Arrays.stream() method internally.

2. Primitive arrays

In case of primitive arrays, Stream.of() and Arrays.stream() return different types. Following are the overloaded versions of Arrays.stream():

  • static DoubleStream stream(double[] array)
  • static DoubleStream stream(double[] array, int startInclusive, int endExclusive)
  • static IntStream stream(int[] array)
  • static IntStream stream(int[] array, int startInclusive, int endExclusive)
  • static LongStream stream(long[] array)
  • static LongStream stream(long[] array, int startInclusive, int endExclusive)
  • static Stream stream(T[] array)
  • static Stream stream(T[] array, int startInclusive, int endExclusive)

Following are the overloaded versions of Stream.of() method:

  • static Stream of(T… values)
  • static Stream of(T t)
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class ArrayToStreamExample {

	public static void main(String[] args) {
		int[] intArray = { 1, 2, 3, 4, 5 };

		// Using Arrays.stream()
		IntStream intStream1 = Arrays.stream(intArray);
		System.out.println("Iterating Arrays.stream result");
		intStream1.forEach(x -> System.out.println(x));

		// Stream.of() returns Stream<int[]>
		Stream<int[]> streamIntArray = Stream.of(intArray);

		// Since it is stream of array, you need to flat
		IntStream intStream2 = streamIntArray.flatMapToInt(x -> Arrays.stream(x));
		System.out.println("Iterating IntStream");
		intStream2.forEach(x -> System.out.println(x));
	}
}

Output

Iterating Arrays.stream result
1
2
3
4
5
Iterating IntStream
1
2
3
4
5