How to convert Array to Stream
Hi friends,
i am going to explain how to convert Array to Stream in Java8.
you can convert an array to a stream using the Arrays.stream()
method for arrays of primitive types (e.g., int[], double[], etc.) and arrays of objects.
or using the Stream.of()
method for arrays of objects.
- For Primitive Array
int[] intArray = {1, 2, 3, 4, 5};
it will retrun IntStream.
int[] intArray = {1, 2, 3, 4, 5};
// Convert int array to IntStream
IntStream intStream = Arrays.stream(intArray);
double[] doubleArray = {1.0, 2.0, 3.0, 4.0, 5.0};
// Convert double array to DoubleStream
DoubleStream doubleStream = Arrays.stream(doubleArray);
import java.util.Arrays;
import java.util.stream.IntStream;
public class ArrayToStreamExample {
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
// Convert int array to IntStream
IntStream intStream = Arrays.stream(intArray);
// Perform stream operations
intStream.forEach(System.out::println);
}
}
2. For Arrays of Objects:
String[] stringArray = {“apple”, “banana”, “orange”};
return type will be Stream<String>
String[] stringArray = {"apple", "banana", "orange"};
// Convert String array to Stream<String>
Stream<String> stringStream = Arrays.stream(stringArray);
Stream<String> stringStream = Stream.of(stringArray);
Alternatively, you can use Stream.of()
for arrays of objects.
import java.util.Arrays;
import java.util.stream.Stream;
public class ArrayToStreamExample {
public static void main(String[] args) {
String[] stringArray = {"apple", "banana", "cherry"};
// Convert String array to Stream<String>
Stream<String> stringStream = Arrays.stream(stringArray);
// Perform stream operations
stringStream.forEach(System.out::println);
}
}
Note that the Arrays.stream()
method can handle arrays of any type (both primitive types and objects).
but Stream.of() only for Arrays of objects
If you’re working with primitive data types (int, long, double), there are specialized methods like Arrays.stream(int[] array)
, Arrays.stream(long[] array)
, and Arrays.stream(double[] array)
for converting arrays of primitive types to streams.
Keep in mind that once you’ve converted an array to a stream and performed any terminal operation (e.g., forEach, collect), the stream is considered consumed and cannot be reused. If you need to perform multiple operations on the same data, you should create a new stream for each operation.
Thanks & Happy Learning :)