In this Convert Array to Stream in Java post, we show you how to convert a array to stream using use Arrays.stream, Stream.of or List.stream method. Java 8 is so amazing. With lots of new features and Stream APIs Java 8 is one of the best release.
Let’s dig deeper via some examples:
1. Convert Object array to stream
We have the array of String as below:
1 |
String[] array = {"java", "nodejs", "php"}; |
And this array is convert to stream by three ways below.
a) Using Arrays.stream()
1 2 |
//Arrays.stream Stream<String> stream1 = Arrays.stream(array); |
b) Using Stream.of()
1 2 |
//Stream.of Stream<String> stream2 = Stream.of(array); |
c) Using List.stream()
1 2 |
//List.stream() Stream<String> stream3 = Arrays.asList(array).stream(); |
Here is the demo program with three ways
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class ArrayToStream { public static void main(String[] args) { String[] array = {"java", "nodejs", "php"}; //Arrays.stream Stream<String> stream1 = Arrays.stream(array); stream1.forEach(e -> System.out.println(e)); //Stream.of Stream<String> stream2 = Stream.of(array); stream2.forEach(e -> System.out.println(e)); //List.stream() Stream<String> stream3 = Arrays.asList(array).stream(); stream3.forEach(e -> System.out.println(e)); } } |
Output
2. Convert Primitive Array to Stream
We are considering the primitive array below:
1 |
long[] array = {55,88,66,77}; |
And this primitive array is convert to stream by two ways below
a) Using Arrays.stream()
1 2 |
//Arrays.stream -> LongStream LongStream longStream = Arrays.stream(array); |
b) Using Stream.of()
1 2 3 4 |
//Stream.of -> Stream<long[]> Stream<long[]> temp = Stream.of(array); //Cant print Stream<long[]> directly, flat it to LongStream LongStream longStream2 = temp.flatMapToLong(e -> Arrays.stream(e)); |
Here is the demo program with two ways
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class ArrayToStream2 { public static void main(String[] args) { long[] array = {55,88,66,77}; // 1. Arrays.stream -> LongStream LongStream longStream = Arrays.stream(array); longStream.forEach(e -> System.out.println(e)); // 2. Stream.of -> Stream<long[]> Stream<long[]> temp = Stream.of(array); // Cant print Stream<long[]> directly, flat it to LongStream LongStream longStream2 = temp.flatMapToLong(e -> Arrays.stream(e)); longStream2.forEach(e -> System.out.println(e)); } } |
Output
1 2 3 4 5 6 7 8 |
55 88 66 77 55 88 66 77 |
That’s all about Convert Array to Stream in Java.
References
Arrays JavaDoc
Stream JavaDoc
Download complete source code, click link below
Java8ArrayToStream.zip (216 downloads)