144

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?

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
adam.kubi
  • 1,753
  • 3
  • 13
  • 14

6 Answers6

213

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.

Community
  • 1
  • 1
sol4me
  • 15,233
  • 5
  • 34
  • 34
  • 1
    Well, there IS a difference if your array is an array of primitive types; for instance, `Arrays.stream(someIntArray)` will return an `IntStream`. – fge Jan 11 '15 at 15:24
  • 9
    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` whereas `Arrays.stream` will give you back an `IntStream` which is probably what you want. So +1 – user2336315 Jan 11 '15 at 15:27
  • @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`, 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. – Dima Jan 11 '15 at 15:52
  • 1
    @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 Jan 11 '15 at 15:58
  • 1
    @Dima Could you explain what wrong information is mentioned in my answer? – sol4me Jan 11 '15 at 15:59
  • 1
    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 Jan 11 '15 at 16:01
  • 2
    @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). – user2336315 Jan 11 '15 at 16:03
  • @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`. – Dima Jan 11 '15 at 16:06
  • 3
    @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` back) :-) – user2336315 Jan 11 '15 at 16:11
  • 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. – Dima Jan 11 '15 at 16:17
  • 3
    `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` of size `1`… – Holger Jan 11 '15 at 16:46
  • `Stream.of(array).skip(n).limit(m)` is the idiomatic way to get a stream over a range. – Dima Jan 11 '15 at 16:53
  • 4
    @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. – Stuart Marks Jan 11 '15 at 23:23
  • @StuartMarks why is "preferable"? I mean, when dealing with *streams*, at which point does knowing the size become important in your view? – Dima Jan 11 '15 at 23:47
  • 1
    @Dima The underlying spliterator can split more effectively, leading to more efficient parallelism. – Stuart Marks Jan 12 '15 at 00:00
  • @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? – Dima Jan 12 '15 at 00:07
  • 2
    @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. – Stuart Marks Jan 12 '15 at 03:00
  • 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 Jan 12 '15 at 03:07
  • @StuartMarks look [here](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/stream/Stream.java?av=f#1000) for example – Dima Jan 12 '15 at 03:18
  • @StuartMarks no, I am, not. – Dima Jan 12 '15 at 12:09
  • 6
    For readers who are interested in seeing this little drama concluded, `Arrays.stream(array,start,end)` returns a `Stream` whose implementation is [here](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/stream/ReferencePipeline.java#ReferencePipeline.Head), whereas `Stream.of(array).skip().limit()` returns a `Stream` whose implementation is within [this method](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/stream/SliceOps.java#SliceOps.makeRef%28java.util.stream.AbstractPipeline%2Clong%2Clong%29). – Stuart Marks Jan 13 '15 at 01:47
43

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.

fge
  • 119,121
  • 33
  • 254
  • 329
  • Actually `Stream.of(someArray)` will create a stream of arrays: `Stream`. There's also `Stream.of()` using a single parameter so the compiler doesn't know that you want the one with varargs. – a better oliver Jan 11 '15 at 15:34
  • For a `LongStream`, you'll want to do `LongStream.of`. – Dima Jan 11 '15 at 16:02
  • 1
    @Dima sure, but `Arrays.stream()` works for that as well – fge Jan 11 '15 at 16:20
  • @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". – Dima Jan 11 '15 at 16:28
  • 1
    @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 Jan 11 '15 at 16:47
  • 2
    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 – fge Jan 11 '15 at 16:53
  • 1
    @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. – Dima Jan 11 '15 at 17:37
  • 2
    @Dima and so is yours; _you_ consider `Arrays.stream()` not to be convenient, _I_ consider it to be convenient. Enough said. – fge Jan 11 '15 at 18:11
  • 1
    @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? – Dima Jan 11 '15 at 18:53
  • 2
    @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). – fge Jan 11 '15 at 19:01
  • 1
    @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. – Dima Jan 11 '15 at 19:14
  • 1
    @Dima you never stop, do you? I simply find it more convenient to use, full stop. What don't you understand about it? – fge Jan 11 '15 at 19:15
  • 3
    @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**. – Jeroen Vannevel Jan 11 '15 at 19:19
  • @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. – Dima Jan 11 '15 at 19:58
  • 1
    @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. – fge Jan 11 '15 at 20:15
  • @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. – Dima Jan 11 '15 at 20:26
  • 1
    @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. – fge Jan 11 '15 at 20:36
  • @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? – Dima Jan 11 '15 at 20:40
  • 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. – Rodney P. Barbati Nov 03 '16 at 22:59
15
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.

Dima
  • 39,570
  • 6
  • 44
  • 70
  • 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` instead of `Stream`? Also, is there any technical reasoning why there are specialized Stream classes for primitives? – asgs Jun 24 '17 at 17:42
  • 2
    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). – Dima Jun 25 '17 at 02:10
  • Ah, since `int[]` is an `Object`, it would match the overloaded method `of(T t)` and hence it returns `Stream`. So, theoretically speaking, if this method were not available, we would have got the `Stream` 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...` – asgs Jun 26 '17 at 06:43
  • 1
    No, we'd still not get `Stream` that way, because `Stream.of(t ... T) ` would still match the same way. – Dima Jun 26 '17 at 10:43
1

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();
Kaplan
  • 2,572
  • 13
  • 14
0

You can make it also by low level method which has parallel option:

Update: Use full array.length (not length - 1).

/** 
 * Creates a new sequential or parallel {@code Stream} from a
 * {@code Spliterator}.
 *
 * <p>The spliterator is only traversed, split, or queried for estimated
 * size after the terminal operation of the stream pipeline commences.
 *
 * @param <T> the type of stream elements
 * @param spliterator a {@code Spliterator} describing the stream elements
 * @param parallel if {@code true} then the returned stream is a parallel
 *        stream; if {@code false} the returned stream is a sequential
 *        stream.
 * @return a new sequential or parallel {@code Stream}
 *
 * <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel)
 */

StreamSupport.stream(Arrays.spliterator(array, 0, array.length), true)
merqlove
  • 3,674
  • 1
  • 23
  • 22
0

You can use Arrays.stream :

Arrays.stream(array); 

This ensures the return type of steam based on your array input type if its String [] then return Stream<String>, if int [] then returns IntStream

When you already know input type array then good to use specific one like for input type int[]

 IntStream.of(array); 

This returns Intstream.

In first example, Java uses method overloading to find specific method based on input types while as in second you already know the input type and calling specific method.

vipul patel
  • 668
  • 4
  • 7