The Wayback Machine - https://web.archive.org/web/20240717043224/https://www.geeksforgeeks.org/difference-between-stream-of-and-arrays-stream-method-in-java/
Open In App

Difference between Stream.of() and Arrays.stream() method in Java

Last Updated : 03 Mar, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Arrays.stream()

The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: 

Java




// Java program to demonstrate Arrays.stream() method
 
import java.util.*;
import java.util.stream.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        // Creating a String array
        String[] arr = { "Geeks", "for", "Geeks" };
 
        // Using Arrays.stream() to convert
        // array into Stream
        Stream<String> stream = Arrays.stream(arr);
 
        // Displaying elements in Stream
        stream.forEach(str -> System.out.print(str + " "));
    }
}


Output:

Geeks for Geeks 

Stream.of()

The Stream of(T… values) returns a sequential ordered stream whose elements are the specified values. Stream.of() method simply calls the Arrays.stream() method for non-primitive types. Example: 

Java




// Java code for Stream of(T... values)
// to get a sequential ordered stream whose
// elements are the specified values.
 
import java.util.*;
import java.util.stream.Stream;
 
class GFG {
 
    // Driver code
    public static void main(String[] args)
    {
        // Creating an Stream
        Stream stream = Stream.of("Geeks", "for", "Geeks");
 
        // Displaying the sequential ordered stream
        stream.forEach(str -> System.out.print(str + " "));
    }
}


Output:

Geeks for Geeks 

These both methods are the two most commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream<T> when called with a non-primitive type T.

Difference between Arrays.stream() and Stream.of()

Even if Stream.of() is a wrapper over the Arrays.stream() method, there are certain point of differences which clarifies as when to use a Arrays.stream() or when to use Stream.of(). Below are some of the differences between the above two stated methods:

  1. Different return types: For primitives arrays (like int[], long[] etc), Arrays.stream() and Stream.of() have different return types. Example: Passing an integer array, the Stream.of() method returns Stream whereas Arrays.stream() returns an IntStream. 

Java




// Java program to demonstrate return type
// of Arrays.stream() and Stream.of() method
// for primitive arrays
 
import java.util.*;
import java.util.stream.*;
 
class GFG {
 
    public static void main(String[] args)
    {
        // Creating an integer array
        int arr[] = { 1, 2, 3, 4, 5 };
 
        // --------- Using Arrays.stream() ---------
 
        // to convert int array into Stream
        IntStream intStream = Arrays.stream(arr);
 
        // Displaying elements in Stream
        intStream.forEach(str -> System.out.print(str + " "));
 
        // --------- Using Stream.of() ---------
 
        // to convert int array into Stream
        Stream<int[]> stream = Stream.of(arr);
 
        // Displaying elements in Stream
        stream.forEach(str -> System.out.print(str + " "));
    }
}


Output:

1 2 3 4 5 [I@404b9385 
  1. Stream.of() needs flattening whereas Arrays.stream() does not: As the ideal class used for processing of Streams of primitive types are their primitive Stream types (like IntStream, LongStream, etc). Therefore Stream.of() needs to be explicitly flattened into its primitive Stream before consuming. Example: 

Java




// Java program to demonstrate need of flattening
// Stream.of() method returned type for primitive arrays
 
import java.util.*;
import java.util.stream.*;
 
class GFG {
 
    public static void main(String[] args)
    {
        // Creating an integer array
        int arr[] = { 1, 2, 3, 4, 5 };
 
        // --------- Using Arrays.stream() ---------
 
        // to convert int array into Stream
        IntStream intStream = Arrays.stream(arr);
 
        // Displaying elements in Stream
        intStream.forEach(str -> System.out.print(str + " "));
 
        // --------- Using Stream.of() ---------
 
        // to convert int array into Stream
        Stream<int[]> stream = Stream.of(arr);
 
        // ***** Flattening of Stream<int[]> into IntStream *****
 
        // flattenning Stream<int[]> into IntStream
        // using flatMapToInt()
        IntStream intStreamNew = stream.flatMapToInt(Arrays::stream);
 
        // Displaying elements in IntStream
        intStreamNew.forEach(str -> System.out.print(str + " "));
    }
}


Output:

1 2 3 4 5 1 2 3 4 5 
  1. Stream.of() is generic whereas Arrays.stream is not: Arrays.stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays.stream() won’t work. On the other hand, Stream.of() returns a generic Stream of type T (Stream). Hence, it can be used with any type. Example:
    • For Arrays.stream() method: 

Java




// Java program to demonstrate return type
// of Arrays.stream() method
// for primitive arrays of char
 
import java.util.*;
import java.util.stream.*;
 
class GFG {
 
    public static void main(String[] args)
    {
        // Creating a character array
        char arr[] = { '1', '2', '3', '4', '5' };
 
        // --------- Using Arrays.stream() ---------
        // This will throw error
 
        // to convert char array into Stream
        Arrays.stream(arr);
    }
}


  • Output:

Compilation Error in java code :- prog.java:20: error: no suitable method found for stream(char[]) Arrays.stream(arr); ^

  • For Stream.of() method: 

Java




// Java program to demonstrate return type
// of Stream.of() method
// for primitive arrays of char
 
import java.util.*;
import java.util.stream.*;
 
class GFG {
 
    public static void main(String[] args)
    {
        // Creating a character array
        char arr[] = { '1', '2', '3', '4', '5' };
 
        // --------- Using Stream.of() ---------
        // Will work efficiently
 
        // to convert int array into Stream
        Stream<char[]> stream = Stream.of(arr);
 
        // Displaying elements in Stream
        stream.forEach(str -> System.out.print(str + " "));
    }
}


Output:

[C@548c4f57 


Similar Reads

Character Stream Vs Byte Stream in Java
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of no
4 min read
Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
Arrays stream() method in Java
stream(T[] array) The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Syntax: public static &lt;T&gt; Stream&lt;T&gt; stream(T[] array) Parameters: This met
3 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Difference Between Collection.stream().forEach() and Collection.forEach() in Java
Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working. Collection.stream().forEach() is basically used for iteration in a group of objects by converting a
3 min read
Difference Between map() And flatMap() In Java Stream
In Java, the Stream interface has a map() and flatmap() methods and both have intermediate stream operation and return another stream as method output. Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value, whereas flatMap() function produces an arbitrary n
3 min read
Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Stream | Collectors toCollection() in Java
Collectors toCollection(Supplier&lt;C&gt; collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed. Syntax: public static &lt;T, C extends Collection&lt;T&gt;&gt; Collector&lt;T, ?, C&gt; toCollection(Supp
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg