How can I create a stream from an array?

66,394

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();
Share:
66,394
adam.kubi
Author by

adam.kubi

Updated on October 23, 2020

Comments

  • adam.kubi
    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
    fge over 9 years
    Well, there IS a difference if your array is an array of primitive types; for instance, Arrays.stream(someIntArray) will return an IntStream.
  • user2336315
    user2336315 over 9 years
    This answer is better because Arrays.stream has all the overloaded cases for primitive arrays. I.e Stream.of(new int[]{1,2,3}) will give you a Stream<int[]> whereas Arrays.stream will give you back an IntStream which is probably what you want. So +1
  • a better oliver
    a better oliver over 9 years
    Actually Stream.of(someArray) will create a stream of arrays: Stream<long[]>. There's also Stream.of() using a single parameter so the compiler doesn't know that you want the one with varargs.
  • Dima
    Dima over 9 years
    @user2336315 You don't want to do Stream.of(new int[]{1,2,3}). Just do Stream.of(1,2,3). It'll give you Stream<Integer>, which is functionally more or less equivalent to IntStream. Also, I am not the "downvoter", but I guess one reason for downvoting this answer might be, that it is (1) wrongly talks about Stream.of(int[]), and (2) the OP has never asked about int streams to begin with.
  • sol4me
    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 using Stream.of because it doesn't make assumption of What is the original type of array
  • sol4me
    sol4me over 9 years
    @Dima Could you explain what wrong information is mentioned in my answer?
  • Dima
    Dima over 9 years
    I 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 an IntStream. BTW, if you want IntStream, just use IntStream.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
    Dima over 9 years
    For a LongStream, you'll want to do LongStream.of.
  • user2336315
    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
    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
    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 call Arrays.asList with a primitive array and that people expect a List<Integer> back) :-)
  • Dima
    Dima over 9 years
    Well, people, who "expect" a function to return something despite the declared return type don't get much of my sympathy anyway :) Arrays.stream and Stream.of are equivalent functionally. The latter is just more readable and more idiomatic, that's all.
  • fge
    fge over 9 years
    @Dima sure, but Arrays.stream() works for that as well
  • Dima
    Dima over 9 years
    @fge yes, it does. Stream.of just reads better. The whole Arrays thing is just a pretty ugly workaround for a design flaw in java where arrays aren't "real objects".
  • Holger
    Holger over 9 years
    Arrays.stream supports streaming a range of the array, which IntStream.of doesn’t. In contrast, Stream.of is the better choice if you want a Stream<int[]> of size 1
  • Dima
    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
    Dima over 9 years
    Stream.of(array).skip(n).limit(m) is the idiomatic way to get a stream over a range.
  • fge
    fge over 9 years
    Well, as to streams, convenience! No need to call *Stream.of() when you have Arrays.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
    Dima over 9 years
    @fge What us "convenient" about Arrays.stream compared to Stream.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
    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
    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
    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 prefer Arrays.stream() for such cases, which makes it wrong as a general rule that Stream.of() is more convenient (Peano algebra).
  • Dima
    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
    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
    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
    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
    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
    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
    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
    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
    Stuart Marks over 9 years
    @Dima 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.
  • Dima
    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
    Stuart Marks over 9 years
    @Dima The underlying spliterator can split more effectively, leading to more efficient parallelism.
  • Dima
    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
    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
    Dima over 9 years
    Nah. "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
    Dima over 9 years
    @StuartMarks look here for example
  • Dima
    Dima over 9 years
    @StuartMarks no, I am, not.
  • Stuart Marks
    Stuart Marks over 9 years
    For readers who are interested in seeing this little drama concluded, Arrays.stream(array,start,end) returns a Stream whose implementation is here, whereas Stream.of(array).skip().limit() returns a Stream whose implementation is within this method.
  • Rodney P. Barbati
    Rodney P. Barbati over 7 years
    I 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
    asgs almost 7 years
    What I don't understand is, when an int[] can be passed to a method accepting varargs, why won't Stream.of(intArray) produce a Stream<Integer> instead of Stream<int[]>? Also, is there any technical reasoning why there are specialized Stream classes for primitives?
  • Dima
    Dima almost 7 years
    Java primitives are weird beasts. int[] isn't like other arrays. It's not a subclass of Object[], but it is a subclass of Object. So, when you pass it to Stream.of, it's taken as the Object, parameter, and you get a stream of int[]. 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 the Object overhead from boxing (converting int to Integer to make it look like normal objects).
  • asgs
    asgs almost 7 years
    Ah, since int[] is an Object, it would match the overloaded method of(T t) and hence it returns Stream<int[]>. So, theoretically speaking, if this method were not available, we would have got the Stream<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 as T...
  • Dima
    Dima almost 7 years
    No, we'd still not get Stream<Integer> that way, because Stream.of(t ... T) would still match the same way.