4

I'm looking for a way to convert an Iterable into a Stream in a lazy fashion in Java 8. Does anyone know of a nice way to do this Java 8?

What I've tried so far is:

StreamSupport.stream(myIterable.spliterator(), false);

Is this the best way to do it?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Johan
  • 37,479
  • 32
  • 149
  • 237
  • 1
    Yes, I don't see any better way. – JB Nizet Apr 08 '14 at 07:05
  • It's not a duplicate. The OP is asking for a lazy stream generation. – Rafael Winterhalter Apr 08 '14 at 08:50
  • 1
    @raphw `spliterator()` is lazy. – assylias Apr 08 '14 at 08:58
  • 1
    Isn't **every** stream lazy by definition *until* a terminating operation is called? – Honza Zidek Apr 08 '14 at 10:54
  • 1
    @HonzaZidek: the stream itself is lazy, but if you did, for example Lists.newArrayList(iterable).stream() to construct the stream, the construction of the stream wouldn't be lazy. – JB Nizet Apr 08 '14 at 11:26
  • @JBNizet: What exactly do you mean by "the construction of the stream wouldn't be lazy"? I believe the stream items will not materialize until you call a terminating operation, so the stream will not iterate through the collection. That's what I understood under the term "lazy construction". – Honza Zidek Apr 08 '14 at 13:21
  • I mean that Lists.newArrayList(iterable).stream() would iterate through the iterable to copy all its elements to an ArrayList, which would then be transformed into a Stream. – JB Nizet Apr 08 '14 at 13:37
  • Why do you think so? I looked at the source code of ArrayList.stream(), it just uses the default implementation from Collection, which calls StreamSupport.stream(spliterator(), false). ArrayList defines its own spliterator, but it is just passed to the StreamSupport.stream() which just creates ReferencePipeline.Head. I have not found any iterating through the original ArrayList. Why do you think it does it? – Honza Zidek Apr 08 '14 at 13:49
  • Now I see your point better - the origin is not an ArrayList, but an Iterable. So what would iterate over the iterable is the ArrayList constructor. I somehow supposed that we already *have* an ArrayList. – Honza Zidek Apr 08 '14 at 13:54

0 Answers0