Java streams are sequences of elements supporting sequential and parallel aggregate operations, introduced in Java 8 within the java.util.stream package to process collections of objects in a functional style. They serve as a declarative tool for filtering, mapping, sorting, and reducing data without modifying the original source.
Key Concepts and Operations
Stream vs. Collection: Unlike collections which store data, streams do not store elements; they derive data from sources like collections, arrays, or I/O channels and produce results through a pipeline.
Pipeline Structure: A stream pipeline consists of a source, zero or more intermediate operations (e.g.,
filter,map,sorted,distinct,flatMap), and exactly one terminal operation (e.g.,collect,forEach,reduce,count).Lazy Evaluation: Intermediate operations are lazy, meaning computation only occurs when a terminal operation is initiated, allowing for optimized execution.
Functional Style: Streams enable parallel processing and functional programming patterns, allowing developers to express complex data manipulations concisely using lambda expressions.
Types of Streams
| Type | Description | Package |
| Java 8 Streams | Process sequences of objects in memory using functional operations like map and filter. | java.util.stream |
| I/O Streams | Handle input/output of bytes or characters between a source and destination (e.g., files, network). | java.io |
Streams are distinct from I/O streams; while I/O streams manage the flow of data into and out of a program, Java 8 streams manage the processing of that data once it is in memory.
Can someone help me with understanding how Streams in Java work?
use case for Java Streams...
Check out these talks by Venkat Subramaniam. There's one where he talks about "simple vs. familiar" that you need to hear. TL;DR, people often mistakenly say something isn't simple when what they really mean is it's unfamiliar.
Maybe you can figure out how to search the transcripts to find it. But they're all worth watching.
https://youtu.be/1OpAgZvYXLQ
https://youtu.be/WN9kgdSVhDo
https://youtu.be/kG2SEcl1aMM
I like Streams and the map/reduce style (what it's called generically since the term stream is pretty Java specific), because it tells you what it's doing. filter does exactly that. The equivalent with a for loop is an if or continue which isn't as clear because you have to run the code in your head to figure out what it's doing. With a stream I can see that it's filtering and if I want to I can dig into exactly how, but I don't have to get an overall feel for what's going on. Likewise findFirst says exactly what it's doing. break means it's exiting early but doesn't mean it's done after the first thing.
Java streams
well you should experiment a bit, after some time you get an intuitive understanding of what all that stuff do.
In short: stream() produce a continuous sequence of items (depending on the source, for example an array or collection). You can think of it as an assembly line with stuff proceeding on a treadmill. All those methods are like workers operating on the treadmill.
For example, filter() remove stuff based on some validation rule, think of them as inspectors that discard broken items from the production line. You provide the validation rule. It's in the form of a function that takes the object and return true or false (a Predicate). This method obviously can decrease the amount of items on the "production line".
Map() let you transform objects on the line. It reminds me of those "tunnels" in assembly lines where one thing enter and a different one exit. For example, if you have a stream of String, you can process each item and transform it in the uppercase version of it: map(s -> s.toUppercase()). You provide the transformation logic in the form of a Function, it can really do anything, can even return a different class, so a map() can turn a stream of String into a Stream of List or anything else. It doesn't change the number of items on the stream. Sort() should be easy to undertand, the assembly line analogy kind of breaks here but it simply gives you the same stream but with elements sorted in some order, either default or provided by you (a Comparator).
Just as the assembly line, stream methods can be chained, so that the output of the previous worker is the input of the next worker. You could filter(), then map(), then sort(), etc. The map() will not receive items filtered by the upstream filter(), and the sort() will receive object already tranformed by map().
After all that work, objects can be collected, this is the job things like collect() or forEach() methods and Collectors. Items can be poured in a List (Collectors.toList()), processed right there (forEach), distributed in a Map, partitioned, etc etc (just looks at Collectors for how much choice there is).
IHTH, if you have any specific question feel free to ask
More on reddit.comVideos
I have read through multiple guides but I still don't get the concept of streams. What exactly are they and why are they important? Why dont we just use arrayLists instead?
So let me tell you what I am exactly looking for. The basic question is, "Why was Java Stream API introduced so recently? Why wasn't it introduced earlier?" I am listing down the key points of the discussion and my comments(if any) as per my knowledge:
Working on the idea, the algorithm and developing the API took time.
To compete with JavaScript's Array features.
Because Streams are faster than For Loops. (I don't think so. For Loop is faster than Streams.)
To make use of Multi-Core CPUs. (Counter Point: That could've been achieved through a multi-threaded environment.)
So I want to understand the API more precisely. I am curious about the internal working and yes, if someone could answer the base question, it would probably help me end the discussion. Any help is appreciated.
Edit: Peak points of discussion as in the points from what we discussed and not from the discussion over the internet.
I have an hard time understanding a good use case for Java Streams.
My experience is mainly related to Web applications. Most things happens at DB level, or controller level. Business logic not too complex and definitively not handling big arrays.
I had some experience with ETL, but rather on analysing quickly many small files.
I find old for loops much easier to understand and maintain, yes more verbose for sure, but that's it. One-liners with streams look cool, right...
Performance wise, I think I would need to process a load of data to really see a difference.
The only big reason I see to study them it's because they are subject of questions in job interviews...
But I'm sure I am wrong, please give me some light.
Check out these talks by Venkat Subramaniam. There's one where he talks about "simple vs. familiar" that you need to hear. TL;DR, people often mistakenly say something isn't simple when what they really mean is it's unfamiliar.
Maybe you can figure out how to search the transcripts to find it. But they're all worth watching.
https://youtu.be/1OpAgZvYXLQ
https://youtu.be/WN9kgdSVhDo
https://youtu.be/kG2SEcl1aMM
I like Streams and the map/reduce style (what it's called generically since the term stream is pretty Java specific), because it tells you what it's doing. filter does exactly that. The equivalent with a for loop is an if or continue which isn't as clear because you have to run the code in your head to figure out what it's doing. With a stream I can see that it's filtering and if I want to I can dig into exactly how, but I don't have to get an overall feel for what's going on. Likewise findFirst says exactly what it's doing. break means it's exiting early but doesn't mean it's done after the first thing.
I find old for loops much easier to understand and maintain
This is almost certainly a lack of familiarity with them. Once I started using them, I quickly found that I prefer them. When working with lists, which is very often in my experience, they are much easier to read.