Convert Array to Stream in Java 8

In this post, we will discuss various methods to convert array to Stream in Java 8.

 

1. Convert Boxed Array to Stream –

A Stream can be constructed from a boxed array using one of below methods:

 

1.1. Using Arrays.stream()

 

1.2. Using Stream.of()

 

1.3. List.stream()

 

2. Convert Primitive Array to Stream –

When we convert primitive array to Stream, we will get primitive Streams like IntStream, DoubleStream and LongStream. These primitive streams can be obtained by using one of below methods:

 

2.1. Using Arrays.stream()

 

2.2. Using IntStream.of()

 
Note – Arrays.asList(arr).stream() and Stream.of(arr) will return Stream<int[]> not IntStream.

 

3. Filter Array using Stream –

We can also filter an array to match a certain criteria using Streams as shown below:

 

Download   Run Code

Output:

NYC
New Delhi

 

4. Convert Stream back to Array –

Many times we might have a Stream of elements and we want to convert it back to the array. We can easily do so as shown below:

 

Download   Run Code

Output:

[NYC, Mexico, Beijing, New Delhi, Tokyo]

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz