- Podcasts
- The Java Developers Hub
- Java Stream API Explained | Intermediate & Terminal Operations Deep Dive
Java Stream API Explained | Intermediate & Terminal Operations Deep Dive
The Java Developers Hub
- December 3, 2026
- 1 h 0 min
- Episode 18
About this episodeThe Java Stream API provides a powerful and expressive way to process collections of data using functional programming techniques. It…
In this episode, we take a deep dive into Java Stream methods, exploring the differences between intermediate and terminal operations and how they work together to create efficient data-processing pipelines.
You'll learn how to use Stream API methods to write cleaner, more readable, and maintainable Java code while handling collections and complex data-processing tasks.
Whether you're learning modern Java programming or improving your backend development skills, mastering the Stream API is an important step toward becoming a proficient Java developer.
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Java Stream API Explained | Intermediate & Terminal Operations Deep Dive
Welcome back Coder Army to our Java series. And today we are going to go deeper into our streams. We are going to see how many functions and methods are there in the streams. What are the intermediate functions? What are the terminal functions? We will understand everything in depth. You will have a lot of fun. And obviously, you will get to learn a lot. So let's quickly go to the screen and start it.
So we understood about java streams, we saw java streams very well in our last lecture If you haven't seen that lecture, then click on the i button and watch that lecture first, it is very important to understand this So we saw that stream is nothing but a pipeline in which we put many operations one after the other And our data passes through these operations and finally when our stream ends, which we call as our stream is consumed And as soon as our stream gets concluded, we have some set of elements left which must have passed through all these filters or some count or maximum or minimum is left. And we also understood how streams appreciate functional programming a lot, how it brings us from an imperative style of coding to a declarative style of coding. So now let's understand that the source of our stream For example, let's say I have a list And I am calling this list as numbers list There are some numbers like 3, 5, 10, 13, 17, 11 Something like this And I have made my stream like this So I have written, let's say list.stream So I have streamed on this list Now I can write all my intermediate operations As you know, as soon as I write list.stream It means I have written my source So my source is this list. The data of this list will come down from my stream. After that I will write some intermediate functions. For example, I can write a filter. What does this do? I can put some predicate condition in it. For every x maps to x greater than 10. So the same numbers will come which are greater than 10. Apart from that I can write a dot map. We had seen this in the example. where I put a function like a transformation for every x, what do I want? I want x into 2, let's say I want its double value and finally I can write toList and you know this is my terminal function, I write it like this this is my terminal after this my stream ends and finally I am bringing my stream in a list and these two were my intermediate functions intermediate, I bring it here Intermediate functions. So these are some set of operations that I do in my stream. In our stream, there are basically three things. One is source, from where our stream starts. There are some intermediate functions. And finally, we have a terminal condition. And we can call it a terminal function. Now, we are going to see one by one, what are our intermediate functions? And what are our terminal functions? Obviously, you don't have to remember all of them. You will remember the important ones, because you will use them again and again. Otherwise, you know that you have to go to your ID and write a dot in front of the stream. You will get a list of all the set of operations. If you have a big idea of what all it does, you will be able to use it easily. So, let's understand these, which are very important. So, first of all, let's come to the list of intermediate functions. So which intermediate functions can we have? There are some common functions that you must have seen till now and there are some that we haven't used yet. So we will use them once. So first of all, I will list them down. So these are all the intermediate functions that we use the most.
And we are going to see some of them now. Now let's go directly to the code and see them. Let's use them one by one. You will understand better. Yes, so I have made my empty file by doing demo.java. And here we are going to see the methods of our streams. So first of all, let's make a list on which we will apply streams.
So that we can print streams. So you assume, if I stream this list, then I will write list.stream. As soon as I write list.stream, I will get all the functions. Now we know that our practice is to put the dot operator and write it below the streams. We write vertically rather than horizontally because we can make a long list of operations. So first of all, my operation was filter.
If I go inside this filter function, then see this stream is made inside java. because a predicate condition expects from me and again gives me stream in output. All the intermediate functions will return me a stream so that I can apply a function on them again. Now see, because it takes a predicate and predicate we know that any condition can be expressed through lambda. So I can give, let's say x maps to x greater than 10. So I wrote here that the same elements should pass from it which are greater than 10. Which elements are greater than 10? 11, 13 and 34.
I am saying is that the same number should pass which is even number. Because I have written x modulo 2 condition. So here again only 34 is left. And finally I can write dot for each so that I can print them on the screen. ForEach is my terminal function. If we go inside forEach, its return type is void because it is not returning anything because it takes a consumer from inside. And do you know what is the function of a consumer? A consumer only consumes your value. So let's say we give it a consumer.
If I go inside the map function, then again it will return a stream which is obvious. But it will take a function type object. And you know what a function is? It's a transformation in which I can transform a value. So in the first filter, I allowed the same number which is greater than 10. So it will let the same number go ahead of the stream and reject the rest of the numbers. Now this map can convert a value into another form. And you know, our functional interface works on t, r. It converts t to r. We saw this in our lecture on functional interface.
What is flattening operation? You imagine. You have a two-dimensional list. Basically, you have a list of lists. So, let's work on that. Let's comment on this and I'll make a new list. Let's make a new list. Let's say list of integer. I have a two-dimensional list here, which I can call list of list. I can name it, let's say, list2. Okay, equal to. Let's say I write list.off and represent a two-dimensional list here. Now look, every element of this list will be a list itself, so I can make all of them list.off.
Map Let's put a map here, because we didn't read the flat map. And I can write x maps to x into 2. Something like this. And I do dot for each. And here I write system dot out. And here I write println. I can't capture this, so I'll write println and terminate it here. But did it work? No, we got the first error.
So what you have to do is, you can write for every x, here x is a list, right? This list2 has an element which is a list itself. And I can do for every x, x.stream. So basically, the element of list2 which is a list itself, the number of elements in it, convert that into a stream. In fact, I can add another map here. Let's say y maps to y into 2. I had to double its value and this will work. So see what I did. I first streamed on list2. So basically this list So basically I streamed my list on this. Streaming on this means that every element of this will come in my stream. This became my source. Then I did dot map for every x. Here x is the same element. Convert x to stream. So I converted it to stream. I applied a map on it. And said for every y, make it y into 2. So basically I multiplied everyone by 2. And finally, I came out of this element. And I wrote dot for each. And print every element. So let's see if my elements can be printed here.
Okay, if I remove all these useless things that I don't do any map, streamed x directly and then put foreach, will I still print something like this? If I run it now, the answer is absolutely yes. Even now, my two elements are being I still have two elements printed in reference pipeline name.
Because this map, even if you are converting it to stream from inside, but you are putting the for each on a complete list. So the map maintains this structure, maintains our hierarchy. So instead of map, we have a special function which we call flat map. And what is the function of flat map? To flat any collection. To say that I have a list of elements in the first one and in the second one. So what will flat map do? For every element x, it will convert x to stream. So it converted it to stream like 1, 2 and flat it. Flat means it brought it to the same level. So for this, 1, 2, 3, 4 all exist at the root level. So now if I run this, then see my 1, 2, 3, 4 is printed which I expected. In fact, I can now apply my condition. In front of this, I will write. map x maps to x into 2. Something like this. My whole work will still work. All the values will be doubled.
Something like this. So what will sorted do? Obviously, you must be understanding. It will sort this whole list, and finally, it will print my for each. So if I run my streams, So, my 22, 26, 68, everything is sorted. Now, think of one thing. This sorted function is a stateful function. We talked about how streams work. Streams work vertically. First of all, let's say my 1111. Until you get all the elements, how will you be able to sort them? So sorted stateful means things stop here. It needs all the elements first. It will sort them and then send them forward. So 11 is basically double 22 is waiting here.
After everything is done, sorted will start its work. And it will give elements by sorting 4 each. And it will print 4 each. So, we call this as stateful. In fact, many methods are stateful. Many methods are free, independent, stateless. Like filter is stateless. This doesn't mean that I have seen so many elements and not so many. It will filter everything and go away. Similarly, this map is also stateless. What does this mean to anyone else? You already understand that it will not be able to sort until it gets all the elements.
In fact, we can sort it in descending order as well. Because your sorted method is overloaded. So, there is a sorted method in stream.java which doesn't take any argument. And it has another overloaded version which is taken by a comparator. We have understood about comparator. So now let's do one thing, we give a comparator here. Okay, the comparator has a method called compare. So instead of that I can give lambda like a, b and it maps to b-a. So I wrote it upside down, you know when we write like this, what does it mean? We will sort it in descending order. So now if I print this, then my elements will be printed in descending order.
It will keep a track of elements that which element has come many times. And it will let them come only once and not the second time. Now again, you think, will our distinct be stateful or stateless? The answer is that this is also our stateful. Because obviously, to know if any element is repeating, we have to keep the old elements with us.
Right? So, until all the elements can't come to it, It will not let the elements go ahead. So again, this is also our stateful like sorted. So now I have all my unique elements here. But let's say I have some repeated elements here. Let's say 13 is repeated. And let's say 34 is also repeated and so on. So now if I run it without distinct, then I get repeated values. Like 68 came twice, 26 came twice. But now I will do one thing. After sorted, I will put it in last.
So now you see, my work is so easy. What I wanted, I have to perform a set of operations and I am writing it directly. I filtered, mapped, sorted, took out distinct elements and printed them. Now think, how optimised this code is in a traditional way, how beautiful it looks and how easily we can understand it. We know that some operations are performed on a pipeline, and finally we print them. If we would normally write it, we would put if conditions, sort it, make it set from inside if we need distinct values, right? And then we would go and print one element on the screen. By putting a for loop or a foreach loop. But here, we just wrote a list of methods and our work is done. Now we have There are two more methods, one is limit and the other is skip. These two methods are also very interesting. In fact, we have used limit as well. Where does limit work the most? Suppose you have an infinite stream. So what I do is, I make an infinite stream here. So let's say I make an infinite stream which I can make with stream.itrate method.
It takes a seed value and an operator to increment it. So I write it as iterate and here I give a seed value. Let's say start with 1 and how do I do it? x such that x is plus 1. Something like this. In fact, I can also print it here. So let's say I'll write. foreach And here I will write system.out and println something like this. So I can print my data. But the problem is that it is an infinite stream. My values will keep getting printed and I will never stop. So if I print it from now, then you can see that my values are getting printed and it will never stop until my memory gets full. So I will close this. I have closed my code. Here I will put one more condition, limit. So let's say I wrote limit 10. So I said that 10 is my limit. All values should be printed till 10. After that, you go to look. So this works for maximum size. Now if I print, then my 1 to 10 will be printed.
Now 1 to 10 will be printed. I iterated, put a limit of 10 and printed it. Now I can write 100 here. So I will have 100 elements printed. I will have 100 elements printed, and so on. Now, the skip is completely opposite to this, which means that I will skip some elements, as many elements as you say. So, for example, I have set a limit of 100 here. Below this, I will put a skip,. skip. skip and write 5 here. So I am telling you to leave the first 5 elements, I will make its limit from 100 to 10. So skip the first 5 elements and then move on. Okay, so let's see what is printed on the screen. So it was printed on the screen from 6 to 10.
Now see, as it was printed from 1 to 10, so 1 came and passed through the limit because it is the limit of 10. But it skipped because it is 5. So the first 5 elements will be skipped. 2 is also skipped, 3 is also skipped, 4 is also skipped and 5 is also skipped. After that 6 is allowed, 7 is also skipped. After that, 6 elements are allowed. In fact, we can use skip here as well. The normal stream that we were printing distinctly, in the last, I could have written.
Now we are going to see a very interesting method which is called peak. This method generally works for debugging. It is very helpful for debugging. Because it observes elements in a pipeline. What does it mean? Let me remove the skip from here. So let's say I had this stream which had some filter, some map. I was sorting it and getting a distinct value. So here I want to know how my elements used to look like before sorting So I can write something here.peek I wrote system.out and println something like this.
We map them, double them, and peak them. So basically, this will print the first 3 elements. Then our elements will be sorted and distinct. And then this will print something. So let's run it and see. See here, first it printed 22, 68, 26 in this order, 11 doubled to 22, 34 to 68, and 13 to 26.
So basically peak helps us to see in our pipeline that after a particular level or a particular set of operations, how our stream looks like. Now the advantage of this is that I told you that it helps in debugging. The advantage of this is that generally when you put a debugger on the stream, then because it is a pipeline, it is a one shot, your debugger does not enter inside it. It does not know what is going on in the middle. If you start the debugger from here, it will come directly to its end. If you hit next, it means that your debugger will not know about its internal details. So the normal debugger won't work like this. So we use peak to know the current condition of our stream. And that's why we generally use it not only for debugging. It doesn't have any use in production. I hope you understood all the operations. We saw all the operations that we use the most. Now look here, the mapToInt and mapToDouble that we didn't see, we already saw in the last class, which converts our normal stream into an int stream, your mapToStream. And our normal stream It converts a double stream into a double stream. We know that an in-stream, double-stream and a long-stream also exist. And why do they exist? Because if we work on a normal stream, which is double-oriented, it will be auto-boxing and unboxing. So we use our optimized streams, which are primitive streams. Okay, so now we understood what are intermediate operations. Now let's understand a little about terminal operations. So basically list of terminal operations. Okay, now look, we know that our streams are completely lazy. Right, we know that our stream is lazily evaluated. So until we write our terminal operation, our stream will never work.
Until we write this, our stream will not run. So let's see how we can categorize our terminal operations. We put this in some categories. So let's say there will be a terminal operation in which you have to collect your data. So let's say I write one, collecting results. So for this, some terminal operations will exist. For this, we generally have toList, which puts our elements in a list, in the final list, which will pass through all our filters. And another method is collect. Now, collect is a very important method, we will see about it in detail. Apart from this, we categorize some reducing results or reducing terminal operations.
And there are some special methods like sum, max, min, average. And as soon as it counts, something like this. So there are some methods that we generally use with our primitive streams. And if we are using it with normal streams, then we have to first convert our normal stream into a primitive stream. Now we will see this properly. Now obviously, apart from all this, we have some methods that work for searching or let's say matching. So if you want to match an element in your collection or stream then you use these So what are the operations that come in this? So it comes with some functions like findFirst, findAny, anyMatch, allMatch, noneMatch AnyMatch, allMatch and noneMatch return boolean, true or false Basically whether you got a match element or not, all or none Now we will look at it one by one And apart from all these, we have another category which we call Iterations, which help in our stream for Iterations And you know that one is forEach, we have used this a lot And the other is forEachOrdered Now when does this work? This works especially in parallel streams Because till now we have seen that our normal stream is sequential Every single element comes out of that stream But parallel streams use threads So multiple elements can pass through our stream Now because multiple elements can pass through together So it is possible that their order is here and there. For that, our forEachOrdered is useful which maintains this order.
Java empty file because we are going to see our terminal operations which can be terminal operations in the stream. So first of all, our simplest terminal operation is foreach. Now we have used this a lot. Let's do one thing. First of all, we make our own list. So we made a list. So list of let's say integer. So list of integer Let's add some elements here. Let's say list.off 1, 13, 11, 9, and so on. Now you know what I can do. I can stream on this list. stream and after that I can apply some operations in it like I can filter, I don't filter this time I just map this is an intermediate operation for every x map it to x plus 1 so increase everyone to 1, that's all I write and the rest I give my terminal operation for each and here I can write I can pass my method reference system.out println because forEach expects consumer and I can pass method reference instead of it I close it and you know what will happen all my elements will be printed one by one and each value will increase in all of them so if we run it you can see 2, 14, 12 and 10 all the values increased one by one Now see, if instead of foreach, I write foreach ordered, basically this method, ordered. So we have to remove this from here. So tell me, would there.
So we see the benefit of this only when we talk about parallel stream. Because there also it maintains the order. Because in normal stream, our foreach will always work. Because our sequential order is also maintained. Right, so this will also work. So we saw this and we also saw forEachOrdered. Now see, the next method we had was a toList. Okay, toList, which puts all our streams, all the intermediate operations on it and then converts it into a list. So if I write here instead of forEach, Let's say dot toList Something like this And if I go inside it, then see What is its return type? Its return type is a list List of what? List of T It can be of any type So let's say I make it toList And I close it And here I take its value in a list Let's say list of integer Okay I call it list2 And something like this Okay So I have all the elements in list2 Which will be in this One by one a value will be added in all of them And what can I do? Let's say system.out.println println I print this list 2 something like this and will my.
The answer is yes it will be printed see 2, 14, 12 and 10 all these values will be equal to plus ok so I can write 2 list too which will basically convert my stream into a list Now see the most interesting thing, here the list that I make using toList is an immutable list. So I can't add any other value in it. I can't write list2. add, let's say 4. So if I write, then there will be no error on the compiler. But when I run it, then see, my unsupported operation exception will come.
If you want to add something to it, something to it, you can't do it. So instead, we have another method, collect. You can use it. In fact, now we are going to see the same method, which is collect. Now, this collect method is one of the most powerful method in our streams. You are going to see a lot of use of it.
To collect our streams in multiple data structures and in fact in multiple ways. So let's see one by one how we can collect our data. So for example, first of all, I will put the place of the tool list, collect. Now if I go inside this collect method. So see, it takes an object of collector interface from me. So collector, we have an entire interface. Which works on three.
Similarly, in java, we have a class named collectors. We know that like collection and collections, similarly in java, we have an interface, a collector and a utility class, collectors. And in this collectors class, there are a lot of methods that bring us a collector. We will see about this too, slowly, which operations are there. So for now, you can assume, I can write collect, and pass inside, collectors dot 2list, collectors. 2list, something like this. So, my code is working. If I look at it now, my list will be printed completely.
And interestingly, this list is mutable. I can add some elements in this list2. So, if I add 4 at last, then my list should be added. There shouldn't be any problem. And my 4 is added. In fact, if I remove this line, then why is it a to list? I can write to set here and I can also take my entire list in a set. So here I just have to change the set and I do my import. Now I take my entire list in a set, I name it set and I print the set here. So let's see if my entire set will be printed. The answer is yes. In fact, we can take it in a map as well. We will see that function later when we understand the collectors in more depth. Now we will see many more methods of the collectors after some time when we will understand them in depth. Now let's move towards our next method which was reduce. This is also a very interesting function. And what does it do? I had told you that it combines our stream elements into one single value. So basically combine streams or not streams, stream elements into single value. So basically we will have a lot of values and we will convert them into a single value using reduce. So let's see how we can do that. So let's do one thing, I will comment this and I will make a new stream. So let's say I wrote list.off. So let's say I made a new stream on the list I had,. stream. And here I added a method, let's say.
If we go and see, then a binary operator is a functional interface which extends our by function. We have already read about this, about the by function. So, we can pass a lambda expression here, let's say, in reduce. Now, the binary operator expects that it can play with two values, two integer values. So, I can write, let's say, a, b, let's say, maps to a plus b. I can write something like this. Let's understand this first. I said convert the list to stream. I converted it to stream, it became a source. Now whatever element comes in it will reduce. Like two values came, 1 and 13, I reduced it from a plus b.
So 1 came, then 13 came, so 13 plus 1 became 14. Then 11 came here, so 14 plus 11 became 25. Then 9 comes, so 25 plus 9 is 34. And finally, its answer is 34. Now see, what is its return type of reduce? Its return type is an optional class. Now we will understand what it is later. But for now, let's do one thing. We will collect it in an optional of integer. Let's say we call it sum. Here it has a spelling mistake, okay. Now obviously we have to import it. So let's import the optional. So optional of integer sum equal to list dot stream dot reduce. Now if I want to print its value, then I can directly take sum dot get. There is a method called get. Now let me tell you why this optional class is used. First let's see what is printed from sum dot get. So, let's see what is printed by our sum.get.
This is the correct answer. We saw that we added all these, right? And because of optional class, we won't get null pointer exception. Okay, so it saves us from that. We will understand about this in depth. But if you want that we don't get optional, but we get a proper integer, which we can also call int. Let's say int sum, something like that.
After this reduce, there is another overloaded function of this reduce, which takes a lambda expression, which is an accumulator, a binary operator. Like if we go inside this, So, we are taking a binary operator. But we have another reduce. If I come down a little. Which also takes an identity. So, what should I do? If I just put an identity. Let's say 0.
That is, everything would have been added in 1. Now if I had printed them, then my answer would have been 35. Right? So identity is very simple, it is my base value, in this only things will be added And if I am multiplying, let's say A multiply B, then in this only things will be multiplied Now obviously if identity is 0, then everything will be 0, because anything multiplied by 0 is 0 Your answer will be 0, in that case I.
As 1 Now I can store multiplications of all these, 1, 2, 8, 7, right So, I will make it a plus b again. So, again we understood what reduce does. It can contract all the stream elements in a single value. And it takes a binary operator from inside which is a functional interface. So, we can pass a lambda here in two values a comma b such that a plus b, a into b, a minus b. Or if you want to calculate something else, you can pass that too. Now, let's see the next method whose name is count. Obviously, you can understand it from the name. It counts how many elements are there in our stream. Let's say I comment this stream. We make a new stream. Let's say list.stream. Something like this. And here I put some operations. Let's say I put a filter first. X maps to X greater than 10. Again, I am using the same filter that we used earlier. Since all the elements are bigger than 10, we will get 13 and 11. And after that, I will write.
For example, I wrote here x is x greater than 10 and here I write find first find first and obviously find first returns an optional return so again I can't take it in long I can take it in an optional of integer let's say num and I can do num.get here num.get something like this so let's see what will be printed here it should be printed here any number which is greater than 10 and whoever gets it first will print it after that our stream will not run so let's check.
So again, it got 13 first, it stopped here, then short circuit happened, it didn't move forward, so find first works there. So find first works there, when we have to do short circuit, we have to basically stop the stream whenever we get the first element which is fulfilling all these conditions. Whatever first element reached here, it returned it, simple. Now, as findFirst is here, there is a method called findAny. Let's see what findAny is. Again, it returns an optional. Now, just like findFirst, as soon as it gets an element, it will cut the stream, it will become a short circuit.
So in our case, since we have a normal sequential stream, so first 1 will go, then 13, then 11, then 9. Now 1 will filter out here, then 13 will come, 13 will reach here. So find first will also give us 13 answers and find any will also give us 13 answers. But its benefit is seen when we use parallel streams. So in that case, find any gives us more freedom.
Takes a predicate condition. And checks if there is any match which satisfies this predicate condition. And if there is, then it will return true. Otherwise, it will return false. So, if I write any match here. So, if I go to any match, then see, it returns boolean. And takes a predicate condition. So, here I can check, let's say, any match x such that x modulo 2 is equal to 0. Something like this. And here again we will get boolean value So here I will take boolean num And I am printing num using get So I will simply print num like this So see what I want here It will filter all those which are less than 10 i.e. only 13 and 11 are allowed And then any match is asking if there is any number which is even And obviously our answer is false because both 13 and 11 are odd Which can pass from here So if I print it then we will get the answer false So this is any match. If I had an even match, then our answer would have been true. Now we have an all match of any match, which you must have understood. It will see if all the elements are true. All the elements that are passing here should be even. Only then all match will be true, otherwise it will be false. So in this case, it will be false. Right, because all of them are not true. Here we have 13, if I make it 14, in that case, it will be true because all the numbers passing are even.
Now, if I reduce it from 1, let's say I made it 13 again, Now it will be false because there is still an element that is fulfilling this condition. There should be no element that fulfills this condition. So let's say I make it 11. So I made it 13 and 11. So now there is no element that is fulfilling this condition.
Average, Maximum, Minimum Which work with our primitive streams So they can't work with our normal streams So let's say if I put integer instead of boolean Let's say sum And I write here finally.sum So will my stream work? The answer is no. I will get an error. And what will be the error? The method sum is undefined for type stream.
And finally, I will take out the sum and I can print the sum here. Something like this. Now you see, what I am doing is, 1, 13, 11, 9, I have filtered out all of them. All the smaller x's will be removed. So, will I have 13 and 11? I will map them to int. So, I have this int stream. If you go to map to int, its return type is int stream. And it takes a toInt function. And we know that toInt function is a functional interface. We have explained it well. What it does is, it takes t as a parameter and returns primitive int.
In fact, instead of sum, I can write maximum. So my maximum element will come. So if I come inside maximum, it gives me an optional int, not just int. So let's say I give it optional. I'll take it under optional int. Now what is optional int? Again, this is my own class. It helps if any of my stream, the original stream, is empty, then I don't have any problem, we'll understand about it. But for now, let's assume that if we've taken out the optional sum, the maximum number, I'll max it.
It'll give me an integer value. And what am I doing? I'm finding the maximum number. And what is the maximum? 13 and 11 is the maximum because it is coming from the filter. So the answer should be 13. If we run it, then we will get 13. Now in the same way, I can also found out the average. And it returns me an optional double. Like we have an optional int, we have an optional double. And I can do it getAsDouble.
Object of collector interface So what is it expecting from you? An object of collector Now, what is a collector actually? See, collector tells a very simple thing. It is a strategy that if we have a stream, how can I collect all its value? Now, I can collect it in any data structure, right? We saw that we can collect as list, as set, even as map. We can group it, we will.
We can perform many operations on it. But basically, how can I collect it in any way? Similarly, we have a CollectorInterface, so this becomes an interface. We have a utility class named Collectors. Collectors itself is a utility class, so it becomes a class. And it has many methods that give us the object of the collector.
Obviously, it exists in java.util.stream.collectors. The utility class exists here in the stream. Now let's see in which things we can collect our values. So let's see which are the basic collections. So let's put it up like this. So I have three basic collections. One is list, one is to set and one is to map. This is the most basic collection. I can collect my values in list, set or map. Let's quickly use them and see. Yes, demo3. java has been made empty. First of all, I'll copy a list here. Let's say I copied this list here.
And I have to do collector sorry import collectors.toList something like this and I will close it and here I will collect all the values in my new list list of integer let's say I will name it list2 something like this so obviously till now I have not performed any operation so I will perform some operations here so let's say I will put a map here. map x maps to x plus 1 x plus 1, something like this. So I will add each and every one of these elements in the list. And finally, I can print my list here by pressing 2. So let's see what value I get here. I got 2, 14, 12, 10. I have added each and every one of them. This is what we saw. This is our normal collector. Now we can return it in the set as well. So I can write 2 set as well. So I know that I will have to make a set for the list. So now I have to import the set Now you know as soon as I print it All my elements will be printed 2, 10, 12 and 14 Okay, now I have another thing which I call toMap. Now this is an interesting method. First of all, how will our toMap work? It will make a map, but there are two things in the map, key and value. What will be the key and what will be the value in this? And we will have to tell that. So let's say if we go inside this method of toMap, then it takes two functions from me, a keyMapper and a valueMapper. And if you look carefully, both are of function type. So I will have to tell here what my map is going to be. So let's make an integer list first. So let's make a new list. Let's make a list of strings. So let's make some strings of different lengths. So I have made a list of strings and now I am going to make a map. So the return value of this will also be map. So its return value will also be map. Let's say map of Let's remove it from here. Now see, what kind of map will be my return value? I am saying that I will keep for the key, whatever is the length of my string, so let's say one will be 2, one will be 3, and one will be 4.
So what can I do for the key? Let's say for every s, let's say I can write for every x map it to x.length Something like this. And what can I say about the value? So basically this is my key. Whatever key comes, like if A comes, then remove its length. That is my key. So its key is 2, 3, and 4. And what should I do for the value? For every x, map it to, let's say, I want its value, so map it to x only.
So these were the three ways. One was our 2Map, 2Set, and the other was our 2List. These are the most common ways. Now after this, a very interesting way comes which we call grouping by. Grouping by. And we use it a lot in real life. And what does it do? It groups your elements based on some key. Basically, it groups them on some key. Let's see how. So, let's say we had 3 strings here. A, A, B, B, B, C, C, C, C. And let's say there is one more string of 2 lengths. And let's say there is one more string of 3 lengths. But let's say there is one string of 4 lengths.
Now if I remove the map from here And write in collect Collectors Collectors Collectors.groupingBy And what should I pass here? I should pass on the basis of which I have to group them. So let's say I have to group them on the basis of length. So suppose there are 2 strings with 2 lengths, 3 strings with 3 lengths, but there is only one string with 4 lengths. So grouping by, I am grouping it on the length of the string, so for every x map it to x, let's say x.length, something like this. Here will come length, length, something like this. Something like this. And obviously, if I am mapping a particular key based on its length, then I am getting a map whose key is an integer, right? That would be, let's say, length. So, how many strings are there in the length of 2? How many strings are there in the length of 3? How many strings are there in the length of 4? I will get this kind of value. Now, there are two strings in the length of 2.
Because look, what I am doing here is collecting it and group by using length. And what is the benefit of group by? Basically, on a particular key, I can group all my elements, divide them. So, who all will come with length of 2? AA and DD will come. In 3, BBB and EE will come, something like this. And in 4, only one will come, CCCC. So, if I want to group this, then integer will be my key and value will be my list of strings. So, now this is absolutely correct. Now, if I I will print it, then my answer will be something like this, see 2 values in 2, 2 in 3 and 1 value in 4. Now see, its real world use case is very much, this was just an example to explain to you. You think that you have a class, let's say class is employee, okay. Employee you have a class. Now see, there can be a lot of keys in this employee. Now imagine, now imagine that you are streaming maps on your employees, right. So you must have written some such code, you must have written, let's say Employees Let's say you have employees and you have put a stream on it And what you can do on that You can do collect Let's say collectors Collectors.groupingby And suppose you see here department So you can write for every employee emp map it to emp.getdepartment So let's say you write getdepartment getdepartment Right? Something like this. So basically what are you doing? On the basis of its department, you are grouping it. Right? So let's say there are some departments of HR, there are some groups in that, some departments of tech, there are some elements in that, etc. etc. So this is used a lot in real life. If you want to make such a map, on the basis of a key, then it will be used a lot. Now, interestingly, there is a special case of grouping by which we call partitioning by. Now, grouping by can make any number of groups on the basis of key. But partitioning by will make only two groups, true and false. Let's see how. So let's do one thing, let's go back to the same numbers list. ArrayList is 1, 13, 11, 19, 9. And what I'm doing is looping through this list, so list.stream. And here I'm not writing collectors.groupingBy, I'm writing collectors.partitioningBy. Partitioning by, and here I give a predicate condition, let's say for every x map it to, such that x modulo 2 is equal to 0. So I partitioned it in a predicate condition. Now it will give me a map, in which the key will always be boolean, and the value will be list of integer. Something like this. Because x modulo 2 is equal to 0, either it will be true or it will be false. Now if I print my map, then it will be printed in such a way that there are 4 values in false and none in true. Now I make it odd, sorry I make it even, 14. Now there will be one value in my even, basically in true. And there will be 3 values in false. So partitioning by is a special case of grouping by which gives a map of just boolean, list. Partitioning by again can group on the basis of true and false and grouping by can make any number of groups on the basis of key. Now, you can use the mapping function with groupingby. Let's go back to our list of string. I will make a new map of integer, list of string. I will name it mp equal to list.stream. I streamed it on my string list. So basically I streamed it on my string list. And what can I pass here? Let's say I wrote here dot collect. So dot collect. And here I write collectors dot GroupingBy And let's say I give a group id here So I would give for every x map it to x.length Right? On the basis of their length group them Length Something like this And here I would do terminate Something like this And when I would print the map Then I would get this map We already know this Now see there is one more method in this What if I bring a line down on groupingBy Something like this I have already told you on which basis to group Now apart from this, I will pass one more thing here, basically I will use an overload function of this which will take from me, let's say collectors.mapping that basically how I have to map the value,. mapping Now see, here I can write my mapper and downstream So if I go to the mapping function, then again I can take a mapper which is a function and a downstream which is itself a collector Now it is very simple to say, see I can write, let's say I want all the uppercase values. So I simply write, for every x, map it to x dot to uppercase. To uppercase.
So now if I print this map. So see here all my values came in lower case. So let's bring this to a new line so that you can see it clearly. So in this way also I can use a mapping function in my grouping by. Now in the same way, there is another very good method to use our collectors. The method is called joining. Now imagine if I stream in the same way. Let's say list.stream. And this time also write.
I am joining on the basis of hyphen. And see what will be its output. Its output will be let's say a string result. Result is a string. And if I want, I can print this result. So see what will happen. I am saying stream on this. And how do I collect all this? I have to join all this using the delimiter hyphen. So I know what stream will I get? AA hyphen BBB hyphen CCCZ something like this. So, if I print this, So I get this kind of value. So I can do this too. Basically, I combined all the elements using a delimiter. And for that, I used collectors.joining. So there are a lot of methods in collectors. We have groupingby, partitioningby, joining. We can use mapping in this too.
What are the ways to collect your streams. Okay, I hope you enjoyed today. You got to learn a lot. See you in the next video. In which we will talk about the remaining topics in streams. We will see what is optional class. How do we make parallel streams etc. That's all in this video. See you in the next video. Till then, thank you so much.
