Junior
Can a array be converted into a stream?
sobes.tech AI
Answer from AI
Yes, it is possible.
There are several ways:
-
Arrays.stream(): The most common and preferred way.
-
Stream.of(): Suitable for small arrays or when you need to create a stream from a fixed number of elements.
-
Arrays.asList().stream(): Less efficient, as it first creates a list, then a stream from it.
// Example of using Arrays.stream()
int[] intArray = {1, 2, 3, 4, 5};
IntStream intStream = Arrays.stream(intArray);
String[] stringArray = {"a", "b", "c"};
Stream<String> stringStream = Arrays.stream(stringArray);
// Example of using Stream.of()
int[] anotherIntArray = {6, 7, 8};
IntStream anotherIntStream = Stream.of(anotherIntArray[0], anotherIntArray[1]); // Creating a stream from individual elements
Stream<String> stringStreamOf = Stream.of("x", "y", "z"); // Stream from string literals
// Example of using Arrays.asList().stream()
List<String> stringList = Arrays.asList(stringArray);
Stream<String> stringListStream = stringList.stream();