What is Java8 Stream?

I read Java 8 In Action , so I know what Stream is and how to use it. But from the point of view of computer science, all data must be stored as a data structure. So,

  • How to store a stream?

  • How can Stream perform so many operations for many collections (e.g. array, linked list, map)?

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

Thanks!

+8
java java-8 java-stream
source share
3 answers

One of the important differences with Stream compared to Collection is that Stream is designed for lazy pricing. Take an excerpt from JavaDoc

Threads are lazy; the calculation of the source data is performed only when the terminal operation is initiated, and the source elements are consumed only as necessary.

Having an instance of Stream does not guarantee that all elements of this stream will be known. Stream elements are evaluated only when they are required. This reflects functions that are in other functional languages, such as Haskell or Scala. You would use Stream to model endless lists. For example, a stream that can calculate the Fibonacci sequence. It will only calculate the items that were requested. It will not compute all elements since it will never complete.

So, the assumption that you can always store Stream content is incorrect. You would only save the contents of the Stream if it were a finite list whose values ​​were identified. At this point, there is no reason to use Stream over a traditional collection.

+5
source share

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

I.e. That's right: the collection should implement the stream method, which should be implemented, as you explained.

However, the stream interface provides some default methods. Some streaming providers make their own storage, for example. collection. Others do not need storage, for example. providers of natural numbers, suppliers of random numbers.

+1
source share

You can look at the source for Collection.stream() and see how it is processed. There is no magic, it is just plain Java code involving Stream and Spliterators and other related classes.

Stream also does not need to store objects, since they are already saved in the Collection from which Stream is created. The non-parallel flow is actually quite simple.

+1
source share

All Articles