Java 8 – Array to Stream conversion

In the previous article, we seen how to convert Stream to Array using toArray() method of Stream API. This article illustrates about Array to Stream conversion with example and explanation.

1. Array to Stream conversion :

  • There are 2 methods available in Java 8 viz., Arrays.stream() and Stream.of()
  • Both these methods return Stream
  • Using above methods, we can easily convert Array to Stream
  • Once after converting Array to Stream we can apply one/more intermediate operation to play with Stream to get the desired result

1.1 using Arrays.stream() method

  • Below example uses Arrays.stream() method to convert Array to Stream
  • First, we are converting Boxed/Wrapper Integer[] array to Stream
  • Second, we are converting String[] array to Stream of String
package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class ArraysToStream {

	public static void main(String[] args) {

		// 1. Wrapper/Boxed Integer array
		Integer[] intArray = {1,2,3,4,5};
		
		System.out.println("Original Wrapper/Boxed Integer[] array :- \n" 
				+ Arrays.toString(intArray));

		// 1.1 Array to Stream
		Stream<Integer> streamOfInteger = Arrays.stream(intArray);

		// 1.2 print to console
		System.out.println("\nWrapper/Boxed Integer[] array to Stream of Integer :- ");
		streamOfInteger.forEach(num -> System.out.print(num + " "));


		// 2. String[] array
		String[] stringArray = {
				"Power",
				"Motor",
				"Chemical",
				"Consumer",
				"Steel"
		};
		
		System.out.println("\n\n\nOriginal String[] array :- \n" 
				+ Arrays.toString(stringArray));

		// 2.1 Array to Stream
		Stream<String> streamOfString = Arrays.stream(stringArray);

		// 2.2 print to console
		System.out.println("\nString[] array to Stream of String :- ");
		streamOfString.forEach(str -> System.out.print(str + " "));
	}
}

Output:

Original Wrapper/Boxed Integer[] array :- 
[1, 2, 3, 4, 5]

Wrapper/Boxed Integer[] array to Stream of Integer :- 
1 2 3 4 5 


Original String[] array :- 
[Power, Motor, Chemical, Consumer, Steel]

String[] array to Stream of String :- 
Power Motor Chemical Consumer Steel 

1.2 using Stream.of() method

  • Below example uses Stream.of() method to convert Array to Stream
  • First, we are converting Boxed/Wrapper Integer[] array to Stream
  • Second, we are converting String[] array to Stream of String
package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class ArraysToStreamUsingOf {

	public static void main(String[] args) {

		// 1. Wrapper/Boxed Integer array
		Integer[] intArray = {1,2,3,4,5};
		
		System.out.println("Original Wrapper/Boxed Integer[] array :- \n" 
				+ Arrays.toString(intArray));

		// 1.1 Array to Stream
		Stream<Integer> streamOfInteger = Stream.of(intArray);

		// 1.2 print to console
		System.out.println("\nWrapper/Boxed Integer[] array to Stream of Integer :- ");
		streamOfInteger.forEach(num -> System.out.print(num + " "));


		// 2. String[] array
		String[] stringArray = {
				"Power",
				"Motor",
				"Chemical",
				"Consumer",
				"Steel"
		};
		
		System.out.println("\n\n\nOriginal String[] array :- \n" 
				+ Arrays.toString(stringArray));

		// 2.1 Array to Stream
		Stream<String> streamOfString = Stream.of(stringArray);

		// 2.2 print to console
		System.out.println("\nString[] array to Stream of String :- ");
		streamOfString.forEach(str -> System.out.print(str + " "));
	}
}

Output:

Original Wrapper/Boxed Integer[] array :- 
[1, 2, 3, 4, 5]

Wrapper/Boxed Integer[] array to Stream of Integer :- 
1 2 3 4 5 


Original String[] array :- 
[Power, Motor, Chemical, Consumer, Steel]

String[] array to Stream of String :- 
Power Motor Chemical Consumer Steel 

1.3 Working with primitive-types

  • While working with primitive-types arrays like int[], long[], double[] for converting Arrays to Stream, we can use both Arrays.stream() and Stream.of() methods but both of these methods returns different result
  • Arrays.stream() method returns IntStream and it can be iterated/printed directly to console
  • But Stream.of() method returns Stream<int[]> (i.e.; Stream of primitive int[] array)
  • Result of Stream.of() method can’t be iterated/printed directly, so we have to convert it using flatMapToInt() method of Stream and then only it can be iterated/printed to console
package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class ArraysToStreamForPrimitives {

	public static void main(String[] args) {

		// 1. primitive int[] array
		int[] intPrimitiveArray1 = {1,2,3,4,5};
		
		System.out.println("Original primitive int[] array :- \n" 
				+ Arrays.toString(intPrimitiveArray1));

		// 1.1 Array to IntStream using Arrays.stream()
		IntStream intStream = Arrays.stream(intPrimitiveArray1);

		// 1.2 print to console
		System.out.println("\nPrimitive int[] array"
				+ " to IntStream using Arrays.stream() :- ");
		intStream.forEach(num -> System.out.print(num + " "));


		// 2. primitive int[] array
		int[] intPrimitiveArray2 = {6,7,8,9,10};
		
		System.out.println("\n\n\nOriginal primitive int[] array :- \n" 
				+ Arrays.toString(intPrimitiveArray2));

		// 2.1 Array to Stream of int[] using Stream.of()
		Stream<int[]> intArrayStream = Stream.of(intPrimitiveArray2);

		// 2.2 print to console
		System.out.println("\nPrimitive int[] array"
				+ " to Stream of int[] using Stream.of() :- ");
		intArrayStream
		.flatMapToInt(num -> Arrays.stream(num)) // flatMapToInt()
		.forEach(num -> System.out.print(num + " "));
	}
}

Output:

Original primitive int[] array :- 
[1, 2, 3, 4, 5]

Primitive int[] array to IntStream using Arrays.stream() :- 
1 2 3 4 5 


Original primitive int[] array :- 
[6, 7, 8, 9, 10]

Primitive int[] array to Stream of int[] using Stream.of() :- 
6 7 8 9 10 

1.4 Filter an Array and convert to Stream

  • An array of Student information defined for 5
  • We are converting student[] array to Stream using Stream.of() method and also applying filter to get only those Students whose age is less than or equal to 20 using filter() method
package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class FilterAnArrayBeforeConvertingToStream {

	public static void main(String[] args) {

		// Array of students
		Student[] studentArray = {
				new Student(1, "Viraj", 17),
				new Student(2, "Krishnanand", 18),
				new Student(3, "Rishi", 16),
				new Student(4, "Suresh", 23),
				new Student(5, "Aditya", 21)
		};

		// print original Student Array
		System.out.println("Original Student Array :- \n" 
				+ Arrays.toString(studentArray));

		// filter Student age less than 20 and convert to Stream
		Stream<Student> studentStream = Stream
				.of(studentArray)
				.filter(student -> student.getAge() < 20);

		// print to console
		System.out.println("\nStudents with age less-than 20 :- \n");
		studentStream.forEach(System.out::println);
	}
}

Output:

Original Student Array :- 
[
Student [rollNumber=1, name=Viraj, age=17], 
Student [rollNumber=2, name=Krishnanand, age=18], 
Student [rollNumber=3, name=Rishi, age=16], 
Student [rollNumber=4, name=Suresh, age=23], 
Student [rollNumber=5, name=Aditya, age=21]
]

Students with age less-than 20 :- 

Student [rollNumber=1, name=Viraj, age=17]
Student [rollNumber=2, name=Krishnanand, age=18]
Student [rollNumber=3, name=Rishi, age=16]

1.5 Map names of Student to Upper case and convert to Stream

  • An array of Student information defined for 5
  • We are converting student[] array to Stream using Stream.of() method but before that we are mapping Student name to Upper Case using map() method
package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class MapToUpperCaseBeforeConvertingToStream {

	public static void main(String[] args) {

		// Array of students
		Student[] studentArray = {
				new Student(1, "Viraj", 17),
				new Student(2, "Krish", 18),
				new Student(3, "Rishi", 16),
				new Student(4, "Suresh", 23),
				new Student(5, "Aditya", 21)
		};

		// print original Student Array
		System.out.println("Original Student Array :- \n" 
				+ Arrays.toString(studentArray));

		// Map Student name to upper case and convert to Stream
		Stream<Student> studentStream = Stream
				.of(studentArray)
				.map(student -> new Student(
						student.getRollId(), 
						student.getName().toUpperCase(), 
						student.getAge()
						));

		// print to console
		System.out.println("\nStudents name in Upper Case :- \n");
		studentStream.forEach(System.out::println);
	}
}

Output:

Original Student Array :- 
[
Student [rollNumber=1, name=Viraj, age=17], 
Student [rollNumber=2, name=Krish, age=18], 
Student [rollNumber=3, name=Rishi, age=16], 
Student [rollNumber=4, name=Suresh, age=23], 
Student [rollNumber=5, name=Aditya, age=21]
]

Students name in Upper Case :- 

Student [rollNumber=1, name=VIRAJ, age=17]
Student [rollNumber=2, name=KRISH, age=18]
Student [rollNumber=3, name=RISHI, age=16]
Student [rollNumber=4, name=SURESH, age=23]
Student [rollNumber=5, name=ADITYA, age=21]

2. Exception scenario while converting Array to Stream :

  • We can convert Array to Stream using 2 methods viz.; Arrays.stream() and Stream.of()
  • But both these methods throws NullPointerException if the input array is null

2.1 Arrays.stream()

  • Input array[] is null for Arrays.stream() method
package net.bench.resources.stream.toarray.example;

import java.util.Arrays;

public class ExceptionWhenInputIsNull {

	public static void main(String[] args) {

		// String[] array
		String[] strArray =  null;

		// string concatenation
		String str = Arrays.stream(strArray)
				.reduce("Test", (str1, str2) -> str1 + " " + str2);

		System.out.println("result = " + str);
	}
}

Output:

Exception in thread "main" java.lang.NullPointerException
	at java.util.Arrays.stream(Arrays.java:5004)
	at net.bench.resources.stream.toarray.example.ExceptionWhenInputIsNull
.main(ExceptionWhenInputIsNull.java:13)

2.2 Stream.of()

  • Input array[] is null for Stream.of() method
package net.bench.resources.stream.toarray.example;

import java.util.stream.Stream;

public class ExceptionForStreamOfMethod {

	public static void main(String[] args) {

		// String[] array
		String[] strArray =  null;

		// string concatenation
		String str = Stream.of(strArray)
				.reduce("Test", (str1, str2) -> str1 + " " + str2);

		System.out.println("result = " + str);
	}
}

Output:

Exception in thread "main" java.lang.NullPointerException
	at java.util.Arrays.stream(Arrays.java:5004)
	at java.util.stream.Stream.of(Stream.java:1000)
	at net.bench.resources.stream.toarray.example.ExceptionForStreamOfMethod
.main(ExceptionForStreamOfMethod.java:13)

References:

Happy Coding !!
Happy Learning !!

Java - How to print an Array
Java 8 - Stream to Array conversion using toArray() method