Stream.of() and Arrays.stream() are used to create streams in Java, but they differ in how they handle arrays, especially primitive arrays.Stream.of() creates a stream from values, while Arrays.stream() creates a stream directly from an array with better support for primitive types.
Arrays.stream()
The Arrays.stream(T[] array) method is used to create a sequential stream from an array. It returns a stream whose source is the specified array.
Syntax
static <T> Stream<T> stream(T[] array)
import java.util.*;
import java.util.stream.*;
class GFG {
public static void main(String[] args) {
String[] arr = { "Geeks", "for", "Geeks" };
Stream<String> stream = Arrays.stream(arr);
stream.forEach(str -> System.out.print(str + " "));
}
}
Output
Geeks for Geeks
Explanation:
- A String array named arr is created containing three elements: "Geeks", "for", and "Geeks".
- The Arrays.stream(arr) method converts the array into a sequential Stream<String>.
- The forEach() terminal operation is used to traverse the stream.
- Each element of the stream is printed using a lambda expression.
Stream.of()
The Stream.of(T... values) method returns a sequential ordered stream whose elements are the specified values. For non-primitive types, Stream.of() internally calls Arrays.stream().
Syntax
static <T> Stream<T> of(T... values)
import java.util.stream.Stream;
class GFG {
public static void main(String[] args)
{
Stream<String> stream = Stream.of("Geeks", "for", "Geeks");
stream.forEach(str -> System.out.print(str + " "));
}
}
Explanation:
- The Stream.of() method is used to create a sequential and ordered stream containing the elements "Geeks", "for", and "Geeks".
- The returned stream is of type Stream<String>.
Arrays.stream() vs Stream.of()
Feature | Arrays.stream() | Stream.of() |
|---|---|---|
Purpose | Creates a stream directly from an existing array. | Creates a stream from given values or an array. |
Primitive Arrays | Supports int[], long[], and double[] as primitive streams. | Treats primitive arrays as a single element. |
Return Type | Returns specialized streams like IntStream. | Returns Stream<T> or Stream<primitive[]>. |
Element Processing | Processes primitive array elements individually. | Requires flattening to process primitive elements. |
Performance | More efficient for primitive arrays. | Less efficient due to boxing or flattening. |
Use Case | Best for processing arrays, especially primitives. | Best for creating streams from known values. |