Convert Array to Stream in Java

Array Stream

To convert an Array to a Stream in a Java program, you can follow these steps:

  1. Create an array of elements of any data type.
  2. Import the java.util.Arrays and java.util.stream.Stream packages.
  3. Call the Arrays.stream() method, passing the array as a parameter.
  4. The Arrays.stream() method returns a Stream object, which you can assign to a variable of type Stream.

Here’s an example program that converts an array of integers to a stream and prints the stream elements:

In this example, we create an array of integers called numbers, and then use the Arrays.stream() method to convert it to a stream of integers. We store the resulting stream in a variable called numberStream, and then use the forEach() method to print each element of the stream to the console.

If you have an array of a different type, you can use the appropriate type argument when calling Arrays.stream(). For example, if you have an array of strings, you would use Arrays.stream(strings) to get a Stream<String>.

Note that in this example, we use a method reference System.out::println to print the stream elements. This is a shorthand way of writing a lambda expression that takes an argument and calls the println() method on it. You can also use a lambda expression directly, like this:

Share This Post On: