Java: Convert Array to Stream

Introduction

In this tutorial, we'll be converting a Java Array into a Java Stream for primitive types, as well as objects. This can be done either via Arrays.stream(), as well as Stream.of().

Arrays.stream()

A good way to turn an array into a stream is to use the Arrays class' stream() method. This works the same for both primitive types and objects.

Primitive Types

For primitive types, you can use Arrays.stream() with an array reference as the parameter.

Optionally, you can also specify the range of indices that should be used as the starting and ending point of the stream/array. If these are not supplied, the entire array will be converted:

// Entire array is used for constructing the Stream
Arrays.stream(T[] arr)  
// Construct Stream with a range of elements
Arrays.stream(T[] arr,int start_ind_Include,int end_ind_Exclude) 
)

Let's instantiate an array and convert it into a stream:

long[] array = {2, 5, 9, 10, 15, 18, 56};
LongStream stream = Arrays.stream(array);
System.out.println("Long stream:");
stream.forEach(x -> System.out.print(x + " "));

This results in:

Long stream: 
2 5 9 10 15 18 56 

Similarly, we can create a stream from a range of indices (0,4) by supplying them as the parameters. Note the starting index of the range is included and end index is not included when a range is specified:

LongStream stream = Arrays.stream(array,0,4);
System.out.println("\nLong stream from index 0 to 3:");
stream.forEach(x -> System.out.print(x + " "));

This results in:

Long stream from index 0 to 3: 
2 5 9 10 

Objects

For objects, Arrays.stream() returns a Stream of the specified object. It accepts an array reference and optionally takes in a range of indices. Let's make a String array and convert it into a Stream:

String[] array = new String[]{"John", "Jenny", "Martha", "Adam"};

// Create a Stream
Stream<String> stream = Arrays.stream(array);
System.out.println("Entire array:");
stream.forEach(c -> System.out.println(c));

// Create a Stream from a range
System.out.println("\nSubarray:")
Stream<String> streamWithRange = Arrays.stream(array,0,2);

The above code generates the following output:

Entire array:
John
Jenny
Martha
Adam

Subarray:
John
Jenny

Stream.of()

Primitive Objects

Instead of using the Arrays class, we can also use the goal class - Stream. The of() method, as the name implies, creates a Stream with a given collection, such as an array.

Keep in mind, Stream.of() returns a stream of objects, regardless of the type you're using. You'll have to flatten it for primitive types. The conversion/casting is done automatically for objects, since in that case, the Stream.of() method just calls Arrays.stream().

Let's make a primitive int array:

int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Stream<int[]> stream = Stream.of(array);
System.out.println("\nInt stream: ");
// Need to be flattened to its primitive type
stream.flatMapToInt(Arrays::stream).forEach(x -> System.out.print(x + " "));
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The flattening is done via the Arrays.stream() method, which in this case just adds redundancy to the code. Instead of using Stream.of() on primitive arrays, we can use built-in classes for these such as IntStream.

This code results in:

Int stream: 
1 2 3 4 5 6 7 8 9

Objects

Now, let's create a Stream of String type. We'll then filter out only names that start with the letter 'J':

String[] array = new String[]{"John", "Jenny", "Martha", "Adam"};

Stream<String> stream = Stream.of(array);
System.out.println("Printing only names that start with 'J'...");
stream.filter(string -> string.startsWith("J"))
        .forEach(string -> System.out.pritnln(string));

The code has the following output:

Printing only names that start with 'J'...
John
Jenny

Conclusion

In this article, we've covered the two ways you can create a Stream from an array. This goes for both primitive arrays and object arrays.

The Arrays.stream() method is a straightforward one, which accepts an array reference and an optional range. The Stream.of() method calls Arrays.stream() for object types, while it requires flattening for primitive types.

Last Updated: September 6th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Mehreen SaeedAuthor

I am an educator and I love mathematics and data science!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms