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]

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use ideone or online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of