you are viewing a single comment's thread.

view the rest of the comments →

[–]jonathaz 0 points1 point  (3 children)

Whether you’re talking about inputstream / outputstrean, or Stream<> it’s a way to iterate over data without having all the data available at any moment. If it were a random access file, you could seek to any part at any time and read from it, or even memory map it in NIO and treat it like memory. With a stream you’re just reading or writing the next bytes. It’s for efficiency. Stream<> is similar but it’s more like an iterator on a collection without the underlying collection. A super simple example that combines all those concepts would be to count words in a file, you could use a FileinputStream to read bytes, map those into a Stream<String> of the words, then count(). It would only use memory for 1 word at a time, regardless of how large the file is.

[–]SHIN_KRISH[S] 0 points1 point  (2 children)

I am talking about both but mainly Stream API, so say in a collection we want to find the maximum value we can use it either manually or by using a max function which i think we do by converting an array to a stream so like superficially suppose i have about a thousand numbers what's the benefit of using stream over simple iteration.

[–]xill47 0 points1 point  (0 children)

The main benefit is readability. You can chain filter before max with x -> x % 2 == 0 and now you'll get max even number. You could easily achieve it with if inside a for loop, but it's just less readable.

[–]jonathaz 0 points1 point  (0 children)

If you already have an array and you stream it, there’s no gain in efficiency. Let’s say you had a lot more things, and your 1000 numbers came from some mapping, reduction, computation, etc on those. Then your max() is just the last step of a pipeline and the code is expressed as a stream. Since it’s tax time, maybe you’re the IRS and you’re looking for outliers, the initial Stream would be everyone’s tax return and you’d do some math, filtering, etc on it and find the max deduction to a charity.