Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is Java8's Stream?

I've read Java 8 In Action therefore I know what is Stream and how to use it. But from the point of computer science's view, all data needs to be stored in a kind of data structure. So,

  1. How to store Stream?

  2. How can Stream be able to perform so many operations for so many kinds of collections(e.g., array, linked list, map)?

  3. Or maybe Stream is just an interface and all kinds of collections are required to implement these operations specified in this interface?

Thanks!

like image 986
Neo Avatar asked Apr 08 '15 04:04

Neo


2 Answers

One important difference with a Stream, when compared to a Collection, is that a Stream is meant to be lazily-evaluated. Take the excerpt from the JavaDoc

Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

Having an instance a Stream does not guarantee that all of the elements of that Stream will be known. The elements of the Stream are only calculated when they are required. This reflects features that are in other functional languages like Haskell or Scala. You would use a Stream to model infinite lists. For example, a Stream that can calculate a Fibonacci Sequence. It would only ever calculate the elements that were requested. It would not calculate all of the elements, as it would never complete.

So, the assumption that you can always store the contents of a Stream is not correct. You would only store the contents of a Stream if it were a finite list whose values have all been identified. At that point, there's little reason to use a Stream over a traditional Collection.

like image 161
EdH Avatar answered Sep 30 '22 18:09

EdH


You can look at the source for Collection.stream() and see how it's handled . There's no magic, it's just regular Java code involving Stream objects and Spliterators and other related classes.

Stream also doesn't need to store objects, since they're already stored in the Collection that the Stream is created from. A non-parallel stream is actually quite simple.

like image 25
Kayaman Avatar answered Sep 30 '22 18:09

Kayaman