How to convert a Java array into a Stream

If you ever need to convert a Java array into a Stream, there are at least two ways to do it.

1) Converting an array to a Stream

First, to convert the entire array to a Stream, use the Stream.of static method like this:

import java.util.stream.Stream;

public static void main(String[] args) {
    String[] names = { "joel", "ed", "maggie" };
    
    // here’s the conversion
    Stream<String> namesStream = Stream.of(names);

    namesStream.forEach(System.out::println);
}

That code produces this output:

joel
ed
maggie

2) Converting part of an array to a Stream

If you only want to convert part of an array to a Stream, use the Arrays.stream method, like this:

import java.util.Arrays;

public static void main(String[] args) {
    String[] letters = { "a", "b", "c", "d", "e" };
    
    // convert part of the array to a stream
    Stream<String> stream = Arrays.stream(letters, 0, 3);

    stream.forEach(System.out::println);
}

That code prints this output:

a
b
c

As you might guess from that output, the signature for the Arrays.stream method looks like this:

stream(array, int startInclusive, int endExclusive)

Bonus: Converting varargs parameters to a Stream

As a little bonus, if you need to convert a series of varargs parameters to a Stream, you can also use Stream.of, like this:

Stream<String> namesStream = Stream.of("joel", "ed", "maggie");
namesStream.forEach(System.out::println);

Summary

If you needed to see how to convert a Java array to a Stream, I hope these examples are helpful.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.