To convert an Array to a Stream in a Java program, you can follow these steps:
- Create an array of elements of any data type.
- Import the
java.util.Arrays
andjava.util.stream.Stream
packages. - Call the
Arrays.stream()
method, passing the array as a parameter. - The
Arrays.stream()
method returns aStream
object, which you can assign to a variable of typeStream
.
Here’s an example program that converts an array of integers to a stream and prints the stream elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Arrays; import java.util.stream.Stream; public class ArrayToStreamExample { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; // Convert array to stream Stream<Integer> numberStream = Arrays.stream(numbers); // Print stream elements numberStream.forEach(System.out::println); } } |
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:
1 |
numberStream.forEach(n -> System.out.println(n)); |