How can I create a stream from an array?
Solution 1
You can use Arrays.stream E.g.
Arrays.stream(array);
You can also use Stream.of
as mentioned by @fge , which looks like
public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
But note Stream.of(intArray)
will return Stream<int[]>
whereas Arrays.stream(intArr)
will return IntStream
providing you pass an array of type int[]
. So in a nutshell for primitives type you can observe the difference between 2 methods E.g.
int[] arr = {1, 2};
Stream<int[]> arr1 = Stream.of(arr);
IntStream stream2 = Arrays.stream(arr);
When you pass primitive array to Arrays.stream
, the following code is invoked
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
and when you pass primitive array to Stream.of
the following code is invoked
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
Hence you get different results.
Updated: As mentioned by Stuart Marks comment
The subrange overload of Arrays.stream
is preferable to using Stream.of(array).skip(n).limit(m)
because the former results in a SIZED stream whereas the latter does not. The reason is that limit(m)
doesn't know whether the size is m or less than m, whereas Arrays.stream
does range checks and knows the exact size of the stream
You can read the source code for stream implementation returned by Arrays.stream(array,start,end)
here, whereas for stream implementation returned by Stream.of(array).skip().limit()
is within this method.
Solution 2
Alternative to @sol4me's solution:
Stream.of(theArray)
Of the difference between this and Arrays.stream()
: it does make a difference if your array is of a primitive type. For instance, if you do:
Arrays.stream(someArray)
where someArray
is a long[]
, it will return a LongStream
. Stream.of()
, on the other hand, will return a Stream<long[]>
with a single element.
Solution 3
Stream.of("foo", "bar", "baz")
Or, if you are already have an array, you can also do
Stream.of(array)
For primitive types use IntStream.of
or LongStream.of
etc.
Solution 4
rarely seen, but this is the directest way
Stream.Builder<String> builder = Stream.builder();
for( int i = 0; i < array.length; i++ )
builder.add( array[i] );
Stream<String> stream = builder.build();
adam.kubi
Updated on October 23, 2020Comments
-
adam.kubi over 3 years
Currently whenever I need to create stream from an array, I do
String[] array = {"x1", "x2"}; Arrays.asList(array).stream();
Is there some direct way to create stream from an array?
-
fge over 9 yearsWell, there IS a difference if your array is an array of primitive types; for instance,
Arrays.stream(someIntArray)
will return anIntStream
. -
user2336315 over 9 yearsThis answer is better because
Arrays.stream
has all the overloaded cases for primitive arrays. I.eStream.of(new int[]{1,2,3})
will give you aStream<int[]>
whereasArrays.stream
will give you back anIntStream
which is probably what you want. So +1 -
a better oliver over 9 yearsActually
Stream.of(someArray)
will create a stream of arrays:Stream<long[]>
. There's alsoStream.of()
using a single parameter so the compiler doesn't know that you want the one with varargs. -
Dima over 9 years@user2336315 You don't want to do
Stream.of(new int[]{1,2,3})
. Just doStream.of(1,2,3)
. It'll give youStream<Integer>
, which is functionally more or less equivalent toIntStream
. Also, I am not the "downvoter", but I guess one reason for downvoting this answer might be, that it is (1) wrongly talks aboutStream.of(int[])
, and (2) the OP has never asked about int streams to begin with. -
sol4me over 9 years@Dima I included details as per requested by
mmres1
comment before that I just pasted a single line of code which will return What OP asked. Secondly OP asked how to create Stream from array but he haven't mentioned that array is always of Object type, So this answer is more right then usingStream.of
because it doesn't make assumption of What is the original type of array -
sol4me over 9 years@Dima Could you explain what wrong information is mentioned in my answer?
-
Dima over 9 yearsI don't think it is "more right". It can equally be argued that the OP asked how to create a
Stream
, and not how to create anIntStream
. BTW, if you wantIntStream
, just useIntStream.of
. You can't have a generic piece of code to handle both object and primitive arrays anyway (as long as you want to be type-safe). -
Dima over 9 yearsFor a
LongStream
, you'll want to doLongStream.of
. -
user2336315 over 9 years@Dima I was answering the "How do I create a Stream from an array" My example is simplified to fit in the comment (and yes in this case, I would call also
of
with the values), but you could have defined the int array before wanting to transform it in a Stream. That's why Arrays.stream is better for transforming an array into a Stream (and my example was to show the difference between both, which was not mentioned in the answer at first). -
Dima over 9 years@user2336315, I was responding to your comment, as it was written, and not to the answer that you had in mind. :) Anyway, it is not "better". If you want an IntStream, you use
IntStream.of
. -
user2336315 over 9 years@Dima I guess it's a matter of taste. I mean better in a sense
Stream.of
could give you some surprises (like when you callArrays.asList
with a primitive array and that people expect aList<Integer>
back) :-) -
Dima over 9 yearsWell, people, who "expect" a function to return something despite the declared return type don't get much of my sympathy anyway :)
Arrays.stream
andStream.of
are equivalent functionally. The latter is just more readable and more idiomatic, that's all. -
fge over 9 years@Dima sure, but
Arrays.stream()
works for that as well -
Dima over 9 years@fge yes, it does.
Stream.of
just reads better. The wholeArrays
thing is just a pretty ugly workaround for a design flaw in java where arrays aren't "real objects". -
Holger over 9 years
Arrays.stream
supports streaming a range of the array, whichIntStream.of
doesn’t. In contrast,Stream.of
is the better choice if you want aStream<int[]>
of size1
… -
Dima over 9 years@fge when I said, that the only reason
Arrays
existed was that arrays aren't designed as real objects, and you said it was "not your opinion", you must have meant, that there are other, presumably, better reasons, right? -
Dima over 9 years
Stream.of(array).skip(n).limit(m)
is the idiomatic way to get a stream over a range. -
fge over 9 yearsWell, as to streams, convenience! No need to call
*Stream.of()
when you haveArrays.stream()
when dealing with primitive arrays. And as to arrays not being real objects, well, this is Java, this has been the case since 1.0 so deal with it; brooding over this helps nothing -
Dima over 9 years@fge What us "convenient" about
Arrays.stream
compared toStream.of
? It's longer, harder to use (have to explicitly create array), requires additional import. Which of these "features" do you consider "convenient"? The fact that something has been around for a long time can not in any way be logically construed to mean that that thing is good. This argument is fallacious at its core. -
fge over 9 years@Dima and so is yours; you consider
Arrays.stream()
not to be convenient, I consider it to be convenient. Enough said. -
Dima over 9 years@fge "So is mine" ... what? You find my argument fallacious? Which one? I heard it when you said you found Arrays.stream more convenient, no need to repeat yourself. My question to you was what about it you vonsidere convenient - that it is longer to type, harder to read, more involved to use, or that it introduces additional dependencies to the code?
-
fge over 9 years@Dima yes, I find your argument that
*Stream.of()
is more convenient to be fallacious; because it's a matter of preferences. I preferArrays.stream()
for such cases, which makes it wrong as a general rule thatStream.of()
is more convenient (Peano algebra). -
Dima over 9 years@fge, it is not an argument, it is just a statement. A statement can be right or wrong, but never fallacious. I have not actually argued that Arrays.stream is less convenient. I asked you to explain why you find that it is more convenient. I construe your refusal to explain it as evidence, that you do not in fact have any reason for your belief. As such, it is impossible to argue. A baseless belief is not "a matter of preference", but rather a matter of religion.
-
fge over 9 years@Dima you never stop, do you? I simply find it more convenient to use, full stop. What don't you understand about it?
-
Jeroen Vannevel over 9 years@Dima: it's a matter of preference. The differences are so incredibly tiny that it doesn't matter at all. More specifically: a difference of a few characters is nothing. An additional import to a package inside the standard libraries is nothing. And really, manually creating an array instead of a varargs overload is nothing.
-
Dima over 9 years@JeroenVannevel a few extra characters, or an unnecessary import may not be very significant, but it certainly does not things "more convenient", does it? I kinda agree, it is a matter of preference. If you prefer an object-oriented and/or functional style, you use it, if you are more of an "imperative" guy, you ... stick with "C" :) Just don't say that it is "better" or "more convenient", because it isn't.
-
fge over 9 years@Dima still at that? Now, look; I find
Arrays.stream()
more convenient, you don't, and that's the end of it. END. OF. IT. This discussion has been pointless from the beginning, really. -
Dima over 9 years@fge what's with all the hostility? Like I said, I am not arguing with you at all. I am simply asking if you have any basis to offer to back your belief or if it is purely religious. It is ok, to believe in something blindly, lots of people in the world do just that. So, I am not going to judge you either way. It's just that if you do have a reason for your belief, I would not mind knowing what it is, that's all.
-
fge over 9 years@Dima Well, it's simple... I prefer using
Arrays.stream()
when dealing with arrays because it will do the correct thing whatever the type of the array. Nothing more, nothing less. -
Dima over 9 years@fge But you are always, in any given case, are dealing with a concrete type of the array, aren't you? Why do you find it important, what a different function (that just happens to have the same name) would do to a different array in a situation that has nothing to do with yours?
-
Stuart Marks over 9 years@Dima The subrange overload of
Arrays.stream
is preferable to usingStream.of(array).skip(n).limit(m)
because the former results in a SIZED stream whereas the latter does not. The reason is thatlimit(m)
doesn't know whether the size ism
or less thanm
, whereasArrays.stream
does range checks and knows the exact size of the stream. -
Dima over 9 years@StuartMarks why is "preferable"? I mean, when dealing with streams, at which point does knowing the size become important in your view?
-
Stuart Marks over 9 years@Dima The underlying spliterator can split more effectively, leading to more efficient parallelism.
-
Dima over 9 years@StuartMarks why do you think that? As far as I know, it is the same stream implementation that you end up with, and the same spliterator therefore. Do you have any reason to believe otherwise?
-
Stuart Marks over 9 years@Dima If you create streams the two different ways, get their spliterators, and look at the spliterator implementations and their characteristics, you'll see that they differ. Please try it out yourself.
-
Dima over 9 yearsNah. "Try it yourself" is no argument. If you want to make a point, it is your responsibility to back it up with some evidence, not send your opponent to go look for it themselves. FWIW, I am pretty sure there is no difference, because I have seen the source code.
-
Dima over 9 years@StuartMarks look here for example
-
Dima over 9 years@StuartMarks no, I am, not.
-
Stuart Marks over 9 yearsFor readers who are interested in seeing this little drama concluded,
Arrays.stream(array,start,end)
returns aStream
whose implementation is here, whereasStream.of(array).skip().limit()
returns aStream
whose implementation is within this method. -
Rodney P. Barbati over 7 yearsI think a moderator should have stepped in here and eliminated everything after the word "the". I can probably edit this, but I don't know how yet.
-
asgs almost 7 yearsWhat I don't understand is, when an
int[]
can be passed to a method accepting varargs, why won'tStream.of(intArray)
produce aStream<Integer>
instead ofStream<int[]>
? Also, is there any technical reasoning why there are specialized Stream classes for primitives? -
Dima almost 7 yearsJava primitives are weird beasts.
int[]
isn't like other arrays. It's not a subclass ofObject[]
, but it is a subclass ofObject
. So, when you pass it toStream.of
, it's taken as theObject
, parameter, and you get a stream ofint[]
. That is one of the reasons to have specialized classes for primitive - if you didn't creating streams from primitive arrays would be pretty painful. The other reason, is that specialized classes are more efficient, because the do not need to incur theObject
overhead from boxing (convertingint
toInteger
to make it look like normal objects). -
asgs almost 7 yearsAh, since
int[]
is anObject
, it would match the overloaded methodof(T t)
and hence it returnsStream<int[]>
. So, theoretically speaking, if this method were not available, we would have got theStream<Integer>
in return? or maybe it results in a compilation error because it couldn't find the matching method? i.e.int[]
can't be treated asT...
-
Dima almost 7 yearsNo, we'd still not get
Stream<Integer>
that way, becauseStream.of(t ... T)
would still match the same way.