Convert a Boxed Array to Stream in Java

In this tutorial, we will learn the logic behind converting boxed array to a stream in Java. We will also implement a Java program that demonstration the conversion.

What is Array?

An array is a container object that can store a fixed number of elements of a single datatype. The length of an array is declared when the array is created. After creation of an array, its length remains fixed. Each item in an array is called as element and each element is accessed by its index position ex. array[i]. There are multiple ways of creating an array, one way to create an array is with the new operator.

What is stream?

Java streams represent a data-flow medium through which the data flows. In Stream there are different functions that operate on the data in the stream. Streams they can be used in various programs that involve data-transition functions.

A stream is not a data structure that stores elements; instead, it facilitates elements from a source such as a data structure, an array, a data creator function, or an input/output channel, through a stream of computational operations. Various operations can be performed on the data that is present in stream.

Following is the Java code to convert a Boxed Array to Stream

In this program, we are going to convert the array of strings to a stream using the Arrays.stream() method in Java.

import java.util.*; 
import java.util.stream.*; 

public class array_to_stream
{ 

  public static void main(String[] args) 
  { 
    String[] array = { "Code", "Speedy", "Technologies" }; 
 
    Stream<String> output = Arrays.stream(array); 

    output.forEach(str -> System.out.print(str + " ")); 
  } 
} 

Output:

Code Speedy Technologies

Explanation: In the above Java program, I have declared an array of string type that stores Code Speedy Technologies as three different elements. Then I have declared a Stream named output that will store the converted array elements. The ‘Arrays.stream(array)’ converts the array into stream where array is passed as an argument to the method. Then at the end, using a loop all the elements from the stream are displayed.

 

Leave a Reply

Your email address will not be published. Required fields are marked *