Java 8 FAQ: Top Questions
20. What is the difference between Stream.of() and Arrays.stream() in Java 8?
Both Stream.of()
and Arrays.stream()
are used to create streams in Java 8. The key difference lies in their usage patterns and how they handle arrays and individual elements.
πΊοΈ Step-by-Step Comparison:
- Stream.of(T... values): Takes varargs or individual elements to create a stream.
- Arrays.stream(T[] array): Specially designed to handle arrays and works well with primitive arrays.
π₯ Example Input:
String[] fruits = {"apple", "banana", "cherry"};
π Using Both Approaches:
// Using Stream.of
Stream stream1 = Stream.of(fruits);
// Using Arrays.stream
Stream stream2 = Arrays.stream(fruits);
β Java 8 Solution:
import java.util.stream.*;
import java.util.*;
public class StreamCreationExample {
public static void main(String[] args) {
String[] fruits = {"apple", "banana", "cherry"};
Stream stream1 = Stream.of(fruits);
Stream stream2 = Arrays.stream(fruits);
stream1.forEach(f -> System.out.println("Stream.of: " + f));
stream2.forEach(f -> System.out.println("Arrays.stream: " + f));
}
}
π Detailed Explanation:
- Stream.of() is more flexible for non-array arguments but can treat entire array as a single element if not used carefully.
- Arrays.stream() is more reliable when working directly with arrays, including primitives.
- Avoid
Stream.of(new int[]{1,2,3})
β it will produce one stream of array instead of individual integers.
π οΈ Use Cases:
- Use
Stream.of()
when working with discrete values or object arrays. - Use
Arrays.stream()
for array-specific operations, especially with primitives.