If you want to get a Stream from an array in Java, you can get it by using the Stream.of ()
method or the ʻArrays.stream ()` method.
At first glance, both methods seemed to give the same result, and I didn't know the difference between these methods.
So, when I examined the difference between these two methods, I found that there were two major differences.
When an array of primitive types (eg int []) is used as an argument to these methods, the returned types will be different.
For example, when int [] is used as an argument, the Stream.of ()
method returns Stream
, but the ʻArrays.stream () method returns ʻIntStream
.
Also, the ideal class for processing using a primitive type Stream is a primitive Stream such as ʻIntStream, so if you use the
Stream.of () `method, you need to convert it to a primitive Stream.
It can be converted by using methods such as Stream.flatMapToInt ()
and Stream.flatMapToLong ()
.
When trying to get a Stream from an array of primitive types, the ʻArrays.stream ()` method only supports three primitive types: int [], long [], double [].
So, for example, char [] cannot be used as an argument to the ʻArrays.stream ()` method.
However, the reference type can be used as an argument without any problem.
On the other hand, the Stream.of ()
method has a generic argument, so any type of array can be used as an argument.
The above contents are summarized in Table 1 below.
Table 1. Relationship between each method and the types of arrays that can be used as arguments
Array type used for arguments | Arrays.stream() | Stream.of() |
---|---|---|
double type | ○ | ○ |
float type | × | ○ |
long type | ○ | ○ |
int type | ○ | ○ |
short type | × | ○ |
byte type | × | ○ |
char type | × | ○ |
boolean type | × | ○ |
String type | ○ | ○ |
Class type | ○ | ○ |
From the above, there are differences between the Stream.of ()
method and the ʻArrays.stream ()` method in the return type and the types that can be applied to the arguments, so be especially careful when using an array of primitive types. I found it necessary.
As an individual's impression, I think it's safer to use the Stream.of ()
method.
We would appreciate it if you could let us know what you think about the proper use of these methods.
Thank you for reading to the end.
https://www.geeksforgeeks.org/difference-between-stream-of-and-arrays-stream-method-in-java/ https://docs.oracle.com/javase/jp/11/docs/api/java.base/java/util/Arrays.html https://docs.oracle.com/javase/jp/11/docs/api/java.base/java/util/stream/Stream.html
Recommended Posts