Functional Programming with Java Streams API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on guys assalamu alaikum welcome to amigos code in this video i want to take you through java streams this course is part of the brand new course that i've just released on my website called java streams api and the aim is for you not to write boilerplate code anymore i.e a way to move away from imperative programming to declarative programming you know sometimes we have to define every single moving part of our code creating a list how to loop how to increment the loop how to add to a list how to print how to map how to perform transformations and sometimes we can end up writing hundred lines of code whereas really we just have to write like six or seven so this course is all about making you a better programmer and enabling you to write code that really matters if you're new to my channel go ahead and literally just take two seconds and smash that like button so i can keep on recording videos like this so in this course so on my website you can enroll through this course and basically uh it's more about the functional programming style and if you've done my course on java functions by function consumers by consumers then this course will make fully sense but if not you can enroll to that course it's absolutely for free but in this course we go over what is functional programming stream api understanding transformations with map reduce flat map filtering collectors statistics like sql grouping and sorting and pretty much how the api does work under the hood so basically right here so if i open up you can see that there's quite a lot of videos here and also a bunch of exercises to make sure that you indeed learn from this course if you want to enroll for this course i do have a coupon code so that you can enroll at elf price and enjoy this course if you're new to my channel go ahead and subscribe give me a thumbs up so i can keep on recording these videos and without further ado let's begin this crash course for this course i'm going to be using intellij as the ide of choice but you can use any other ide such as netbeans or eclipse or even vs code if you wish to do so but you'll see that if you use the exact same ide then you'll have no issues running and completing all the exercises so here navigate to jetbrains.com forward idea and download so in here you can either download the ultimate edition or the community edition so download either and you can see that they also have for apple silicon if you have a mac with m1 chips like myself so go ahead and download and install intellij and also actually let me just mention that so yeah so right here i think it's better actually for you to install using toolbox so get the toolbox and then here you can actually install all of the other ides and also update intellij with no issue so you can see that you can update automatically rollbacks downgrades on and so forth so give that a go and make sure to use intellij so that everything works without no issues so in order for you to get started with this course i already have all the examples and the source code prepared which i would like you to use so navigate to this repo github.com amigos code forward slash java dash streams and in here i do have this readme but more important you can see that i do have two branches i've got main and start so let's together clone this in here we can just basically grab this and then you can either use https or ssh so let me just grab this command c and i'm going to open up intellij and in here i'm going to say get from vcs we can pass the url just like so and i can basically say clone and i'm going to clone into users amigos code id project java streams so clone and i'm going to trust everything under this folder and there we go so you can see that i successfully cloned the project here if i close that so what i want to do is in here have a look we have two branches in here at the very bottom right corner so we have main and start so i'm not going to switch just now so what i want to do for you is i want to open up the main folder so java streams and inside i only have src and then test and then java so all the examples for this course will live inside of the test folder in here so this is a maven project that contains all of the dependencies that you need so what i'm going to do is i'm going to right click in here so right click under java so this green folder and then run all tests and you should see that everything should just work so there we go and these are all the examples that you will cover throughout this course so 38 tests did pass now let me hide this and before i explain what's inside here what i want to show you is inside of palm.xml and inside i do have this xml but what i want to show you is that i do have junit guava a cert4j json and then commons.io so if you don't know about testing and you want to learn about unit testing integration mocking all that stuff i do have a course on testing but these are all the dependencies that we need for this course and also i'm using java 17. so here if i go to i think it's under file and then open up project structure and right here have a look project sdk and then open jdk 17 so if you want to follow along with 17 this should work or any other version so here all you have to do is click on edit and then click on plus and then download jdk and then select oracle open jdk 17 and off you go so to be honest this is pretty much the setup that you need for this course next let me walk you through these folders in here so beans examples and mock data so in here i'm inside of this main branch so this is the examples that you will basically complete at the end of this course and let me quickly walk you through this package in here so beans examples and mock data so beans contains pretty much the models that we're going to use for this course so a car class a person class and a person dto now these two classes so car and person they basically are part of the mock data and mock data so mock data if i open this up so this here gives me a list of people and a list of cars now these are json arrays that can be found under resources so cars.json so this is a list of a thousand objects or a thousand cars and the same for people so then i basically just load them inside of this list and then return it back so that we can use it in our tests so if i open up examples let's look at statistics which stream for example right so here you'll see that you have this first line in all of the tests and you can see cars and then we just use it so here we basically say mock data and this is a static method so we just have to say mock data get cars and then we can use it so the same throughout all of these methods you'll see that we are using either cars or so here i can say person right so get people actually so there you have it now what i need to do is so if i close everything go ahead and open up in here you can see that my cursor is right here and i'm navigating to the lower right corner and i'm going to click on main and i want to check out this branch so origin and then start so check out and what this will give you so in here so have a look if i open up distinct and set you can see that uh oh actually let me open the same file i think it was map and reduce have a look all of that code is gone so throughout this course i'm going to be telling you right so open up this file for example or this class and then you can see that i'm using people here and then we'll basically use these classes for learning streams and you'll see all of the examples instead of you having to write all of these tests and classes which there is no need so make sure that you check out the start branch so that you can follow along throughout this course with no issues if you have any questions please do let me know otherwise let's kick off our journey in learning java streams what exactly is the java stream api well to understand that let's focus on the stream itself and in this course we're going to fully learn what exactly is a stream and how it works from top to bottom so a stream is pretty much an abstraction and it focuses on the overall picture instead of each individual part so when you build an application sometimes you pretty much just write a bunch of logic so if this do that if not do that otherwise use a switch statement so on and so forth create an empty list do this do that right so that is the individual pieces right whereas the stream focuses on the overall picture and instead of us defining the implementation as a whole we pretty much just tell it what we want so to understand what i mean so have a look at this piece of code and by the way don't worry too much about this because we're going to go over all of this in detail but in here check this out so this is imperative approach or the imperative programming where we specify every single implementation detail so have a look we have a list another empty list we have a limit we have the counter we loop through the list we have an if statement we add to the list and then we increment the counter then if we reach the limit we break and then at the end we pretty much just print out the contents but you can see that this is a lot of code for something very simple but this is because we are focusing on the individual pieces right so individual parts so we as a developer we have to implement everything and this sometimes can lead to a lot of errors and bugs and instead with streams which allows us to move from imperative to declarative programming we can rewrite the entire thing so have a look so how many lines of code in here 1 2 3 4 5 6 7 8 9 10 11 12 13 14 14 lines or 20 all together right so we can replace all of this with this right here so have a look just this and this is what you're going to be learning in this course right so have a look here we're not defining the if we're not defining an empty list we're not defining how to increment how to stop so on and so forth you can see that we have a list we invoke the stream we filter we tell it how many we want and then we collect back to a list job done and don't you worry about this if you don't understand but at the end of this course you will know everything there is to know about java streams so if you've done my course on functional programming then streams will be very easy for you to understand but basically we move away from imperative to functional programming so instead of us defining every single implementation detail we just tell it what we want now streams are mainly used with collections so if you know about lists arrays sets maps and all that good stuff then you should be good in understanding streams otherwise check my course on java where i go over the collections api so you know what a stream is but how to exactly use a stream so let me actually help you to visualize and hopefully this will make sense so to use a stream we need to start with a collection so this could be arrays sets lists maps and other implementations so now that you have your starting point then what we do is from the list itself we invoke the stream method now from this point onwards we can have as many streams as we want so we can have a stream 1 2 three so on and so forth now these streams right here so this is the abstraction phase so this is telling what we want so this is the abstraction phase right so instead of implementing every single implementation detail we just tell it what we want instead of defining and controlling every single aspect of the logic itself now the stream itself right here and in this course you want to learn about streams and all the methods available but when you invoke the stream on a list or a collection you can have methods such as filter to filter down elements you can map for transformations and also reduce so these three right here are three of many methods available to us and don't worry we're going to cover the most important ones and by the end now something to bear in mind you should know exactly how to work with all of filter map reduce so on and so forth and everything which you can invoke the stream upon these are called the intermediate operators again keep this in mind so these are intermediate operators right then once you are done with your streams and you can have as many as you want you then pretty much just say right so now that i've got my stream i want to go back to a concrete implementation and this is going back for example to a list an integer an object an optional string and any other data type right so these are methods available such as sum collecting to a list performing average grouping by so on and so forth and you'll learn about all of this in this course now i said that the streams itself those are the intermediate operators and at the very end at the very end when you want to collect or you want to go back to a concrete class or type these are called terminal operators and terminal because they end the stream and then they give you back what you pretty much have requested from the sequence of streams and this is pretty much how they work as i said don't worry we're going to cover everything in detail and all the methods available but if you have any questions please do let me know otherwise let's carry on so within examples let me create a new file in here and what i'm going to do is i'm going to call this as working with and then streams so inside of this class in here let me show you how to work with streams so here let me just have a test so new test method and i'm going to say streams there we go and let me collapse this so to work with a stream is as follows so remember i said that we basically start with a list array set so on and so forth so let's have a list in here and this will be a list of strings just like that and let me just say names in here equals to list dot and then off and in here let me say amigos code and then alex and let's just say zara for example right so obviously this could be anything that you want but as i said when you want to work with streams you basically use a collection and then from it you can invoke the streams so here i can say names dot and then have a look stream there we go now this in itself so this in itself if i extract this to a variable have a look so that is a stream of strings so this is the exact same thing of view saying stream there we go and you can specify the data type and then i'm going to say names or basically names and then stream equals to and then stream dot and then we have have a look concat of of or empty generates on it so forth you can even use the builder but here i can say of and then values and i can give the exact same values in here right oops so basically just like that so this is the exact same thing but what i'm doing is from the list itself i'm pulling out the stream right here now from our stream remember i said we can have multiple of methods right so here i can say stream and then dot and now have a look i've got map filter collect limit sorted take while distinct on all of these methods right but what i want you to see is have a look distinct it gives you back a stream take while it gives you back a stream sorted gives back a stream limit gives you back a stream flat map a stream so and so forth so this means that in here you can actually so let me just say limit for example and then two i can then say dot and then basically i can concatenate these streams together right i can say map for example oops so map for example let me just say no in here if i can yes so that's not correct but all i'm showing is that i can say dot and then sorted no and you'll learn how to use all of these in a second but i'm just showing you so basically you see that i'm actually able to concatenate these streams together and once i'm done so here so this is the stream then we invoke so limit map so on and so forth and then at the end we say dot and then collect so these are the terminal operators so let me just say to list and right here so if i extract this to a variable have a look so we have from a stream we piped a bunch of streams together to tell you what we want and then we collect it back to a list of objects now this doesn't do anything i'm just showing you how it works but i'm going to give you real examples in a second all i want to say is that these are the intermediate operators and then once you are done you say collect and this is the terminal operator so i can even say for example so if i delete this so i can delete this and let's say for example count so count have a look count gives me a long and not a list back have a look right so count is also a terminal operator if you want to connect back to a set you can also do it to a map using grouping by but don't worry i'm going to teach you all of that in a second finally what i want to show you is in this course we're going to use both lists and arrays so if you have an array so here if i say string and then names and then array equals two and i'm missing curly brackets here so if i just have an empty array just for now so if i say names dot so here have a look i can say stream and what this does have a look so basically this was auto completion but basically i cannot invoke stream directly into this array i cannot say this so stream you can see that intellij is telling me what i need to do right so instead i need to say arrays dot stream and that will give me back a stream that i can then so here have a look i can say filter map collect so on and so forth right so this is pretty much how you get a stream from an array now this right here doesn't do anything as i said i'm just showing you how to get started with streams but in this course i'm going to give you real examples and by the end of it you will master the streams api let's begin this course with an exercise so open up the getting started class in here inside of tests and what i'm going to do is to complete this method in here so find people age less or equal to 18 then change the implementation to find the first 10 right here so basically there's a bunch of people inside of this list so find the ones which are less or equal to 18 so the actual age and then change your implementation to only return the first 10 people so go ahead and give that a go and again here we're not learning about streams and this is me showing you the imperative approach which then will lead us to declarative approach using streams give that a go and i'm going to give you the solution in the next video all right let me give you the solution for the exercise in here what i did was i created one list right here called young people and initialized to an empty list then i do have two variables so one which is the limit right here which is 10 and then the other one is the counter so this is so that i can only add 10 people into this list right here and then what i have is the for loop for the initial list then i check whether the age is less or equal to 18 if so i add the person to the new list called young people and then here i increment the counter and then i check if the counter is equal to the limit if so then i break out of the loop and finally in here so line 31 i do log or print out to the console the results so here if i run this test so run there we go you can see that so the output have a look so we have in here but if you look at the age in here you'll see that we only have a couple of people back and their age is either 18 or less so there you have it so this you can see that it's a pretty lengthy solution so one two three four five six 7 8 9 10 11 12 13 14 lines of code for something very simple and to be honest we can do something way better than this using the declarative approach with streams join me in the next video so within the same file getting started in here we do have this empty test and this is using declarative approach and streams so what we're going to do is we're going to implement the exact same problem that we have in here by using streams so in here remember i said that we start from a concrete class so our concrete class is people in here now what we need to do is from the concrete we go to the abstraction so here i'm going to say people dot and then stream from this point onwards i can have as many intermediate operators and then the final one which is to collect the results back is the terminal operator so the way that we can replace the above implementation which streams is as follows so here dot and then in here you can see that we have a bunch of methods that we're going to learn throughout this course and the one that i want is filter and inside this takes a predicate so the predicate receives the person so i'm going to say p for person and then it returns a lambda and here this oh actually it takes a lambda and the result has to be a boolean because it's a predicate now here i'm going to say p dot and then get and then h is less or equal to 18 right here and then what i also want to do is say dot and then limit to 10 and finally my terminal operator is dot collect and then to list right here and to be honest this is it so now let me actually put this on a new line so you can see everything properly new line here the same here and then let me extract this to a variable so now i'm going to call this as young and then people same as before and finally we can have the exact same loop so here let me just space that and there we go so don't worry if you don't understand this but basically what we're doing is from the concrete class in here which is a list so this is our starting point we go from the starting point to this abstraction which is using stream then we have two intermediate operations in here so filter and limit and then finally we collect back the results to a type that we can then use which is a list of people so this is the result and then finally we print out the result so if i run this this will give me the exact same result there we go you can see that we have the exact same result in here and if i close this you can see that the implementation in here it's much more elegant than doing all of this logic so you can see that here we have to define you know an extra list and then two variables and then a for loop within a for loop and if statement increment the counter adding to the list checking whether the counter equals to the limit and then breaks you can see how we have to deal with every single part right here so you can see we have to define every single implementation detail whereas with streams in here so the declarative approach we just tell it what we want instead of defining every single step and moving parts for what we want and this is streams in a nutshell don't worry too much about filter limit collect because we're going to learn all of this in this course but you can see the power of java streams if you have any questions please do let me know otherwise catch me on the next one so you saw how of approach is much easier and intuitive to write and it simplifies a lot of things and removes all of the moving parts that we have to implement ourselves now what i want to show you is how to visualize what is happening with streams so basically you saw that we have filter limit and then collectors right here so what i want to show you is there's a nice feature within intellij and that is if i stick a break point in here and then right click and then debug so let's run this together and have a look so it just stopped in here right and if i put this full screen have a look we have this button right here and trace current stream chain so i'm going to click on that now or in fact i don't even need to put this full screen but have a look so i can hide that for now and maybe put this bigger and there we go so have a look what is happening in here so we have people.stream then we filter so if i click on filter have a look this is actually showing me what is happening which is kind of cool right so basically it filtered so all of these people right here and then we have 10 because of limit have a look so we limit into 10 people and then we say collect and then we have an array list of 10 elements so this is really cool so if i click on flat mode you can see that this is actually giving me the entire flow so we have the data we filter right here and then we limit into 10 people and then we collect down this is all for now catch me on the next one all right so in this section let's learn how to filter data with streams so open up the filter class and inside we have this very first test called filter and what i want to do is i want to search for all the cars which have the price less than 2 000 now the way to do this with streams is as follows we say cars dot and then stream and then say dot and then filter now filter takes a predicate and you can see that it has the weight symbol so question mark super and then car so if you want to learn more about generics go and check my course on generics where i teach all of this and also on functional programming i teach predicates consumers buy consumers and all of that good stuff so in here what i want to do is i want to say car and inside here this right here is a predicate and it has to return true or false now i want the car price so car dot and then get price to be less than 20 and then thousands so 20 underscore and then three zero so this makes it easy to read dot and then zero zero so there you have it now obviously we need to collect this to a list so let's just collect this to a list and there we go so if i put this on a new line just like this and this is easy to read now i'm going to extract this to a variable and then i'm going to say cars less than 20k there we go and to be honest this is it so obviously let me just print out to the console the list of cars so here i'm going to say cars less than 20k dot and then for each and then system.out.printline just like that so if i put this with spaces so it's easy to read and let's just run this for a second there we go so you can see that we have a bunch of cars but what i want to show you here is have a look at the prices so you will not see a car which has a price bigger than 20k have a look so there's a bunch of cars here and they're all under 20 000. so if you want to get the ones above 20 000 you just flip this sign so you just say greater and also you need to change the variable but here if i run this you'll see that the cars now will have a higher price so have a look 23 66 000 34 000 so on and so forth so this is the general gist and with filter you can have as many filters that you want right so here let me just put this like this so if i wanted for example to say dot and then filter i can also say car and then car dot and then get color for example so let's just say that uh we want all the yellow cars so here if i basically say dot and then equals and then yellow and then i run this so hopefully we have a yellow card under 20 000 in here so run it and indeed we do have so you can see they are all yellow so yellow yellow yellow yellow and the prices are less than 20k so you can see how you can use filter to filter down data so it's really powerful and one that you should use quite low so in here just to mention so here this is a predicate so if i extract this way variable have a look so that's the predicate the same here if i shrink this to a variable that's another predicate so you can see that this is a predicate and the filter receives a predicate again if you're not sure about predicates go and check my course on functional programming with java where i teach all of this if you have any questions please do let me know otherwise let's move on so in this section let's focus on understanding how to perform transformations with streams and more specifically map flat map as well as reduce so open up the transformations map and reduce class and in here we have this very first test your first transformation with map and here we have a list and this should be people instead of cars so you'll see this line right here and what we want to do is to transform this list right here into a list of a different data type so this is what the map allows us to do it allows us to transform from one data type to another so in the project here inside of beans there is this class called person dto right here and have a look we have one method same map in here so what we want to do is we want to take a person and transform it into the person dto so we want to loop through that list and then transform it to the dto the way to do it is as follows so as always you know how to use streams so people dot n stream now here we can perform lots of intermediate operations but what i really want is to say dot and then map so this is the function that i'm actually teaching you so a map takes so if i press command p have a look it takes a function of type question mark super and then person and then and then comma question mark so if you're not familiar with functions and how they work check my course on java functional programming where i go over all of this but basically what we have to do in here is to pass a function and the function returns something from it right so the map takes the person itself so here let me just say person and what we want to do with this person is the following so here what i want to do is i want to return and then i want to say person and then i want to say new and then person dto and then inside we can say person dot get id person dot and then get first name and then person dot and then get h and in fact sometimes you might see people say p instead of the actual full name but to me it doesn't really matter because i prefer to use the full name so you can see here i'm returning immediately so what you could do also is if i extract this to a variable maybe this is easy for you to read there we go and if i put this on a new line just like that so you see everything right so have a look people.stream and also new line here and what we do is we say map so we want to map the person into this dto and then we return so now that we are done in here and you can also perform filter distinct take while drop while find first and all that stuff right but all i want is to terminate this with collectors and then two and then list and that's all i want now if i press command shift v or control shift v on windows so here let me just name this as um dtos right here and have a look so you can see that we went from one data type so list of person to list of person dto so this is what the map allows us to do and obviously we can then perform a for reach so dtos dot for reach and then system dot out column column print line so if i run this and also let me just say that so assert that i want to show you that the sizes are the exact same thing so i'm not lying to you so let me just put this here and let me import so import static method and the third one so assertions though assert that and here i'm going to say people dot and then size dot is equal to and then dtos dot size so basically i'm just showing you that i'm not taking anything from this i'm not modifying the list all i'm doing is just a transformation so if i run this you should see that everything should work the test should pass and we should have all the details have a look so you can see that we went from a list of person to a list of uh persons dto and you can see this list is quite huge so i think there's a thousand in here and there you have it so obviously you can then perform filters so on and so forth so here for example if before you map you want to say dot and then filter and this takes person and this is a predicate so let's just say for example a person dot and then get age is greater than 20 for example right so if i run this you should see that we should only have people whose age are bigger than 20. and oops so you can see that now the assertion fails because we expected down here for them to be the same size but they're not because i have filtered out few people right so obviously i can then remove this is no longer the case and if i run it you should see the output there we go and you can see all the edges and one thing that i want to show you so before we finish so here what you can do is if you want you can inline this so instead of saying person you can just say here return so this like this so return just like this and then i can remove this one here and also i can remove the return keyword so that's redundant because i can replace it with lambda expression and have a look so this is beautiful stuff so let me just put this on a new line so you can see everything and finally collect so you can see that we went from a list then we have our stream in here we filter we map and then we collect back to a list now finally you see this right here so this map so if i extract this to a variable i just want you to see something have a look so this is actually a function so if you never done functional programming with java this will not make sense to you but this is what it is have a look so it's a function that takes a person and then returns a person dto and then the input is a person and here i'm just returning immediately this new person so there you have it and something that came into my mind is so because in here have a look i do have this method so public static person dto right here so this is a map function that takes person and then returns right here we can actually use it right so basically let me just remove this and i can say person and then person dto method reference and then map so this works because the map takes a person right here and then returns something else well i can pass it to my dto map function because it expects a person and then and then it returns d dto so if i was to extract this to a variable so have a look so it's it's a function it's a function that takes person returns a person dto and then all he does just calls method reference so this is actually pointless so that's why i've inlined it like so so there you have it you have this right here or you can have the map function within your pojos and it's completely up to you how you decide to do things but this is the general idea of the map and basically allows you to transform from one data type to another and bear in mind that we went from a list of person to a list of person dtos but this could be anything that you want literally anything that's all for now catch me on the next one okey dokey i hope that you saw the power of java streams and if you want to enroll to the entire course there is a coupon code right here or maybe somewhere here where you can just click and enroll and get a discount lots of my students have benefited from this course in my previous company we used to use streams quite a lot that's why i decided to record a course specifically on streams because it allows you to write code that really matters instead of having to worry about all the moving parts of your code so if you're not part of the amigos code community go ahead and join both the private facebook group as well as discord the community is growing and i would love to see you there that's all for now i'll catch you on the next one you
Info
Channel: Amigoscode
Views: 34,538
Rating: undefined out of 5
Keywords: amigoscode, java streams api, java tutorial, functional programming, functional programming tutorial, java functional programming, java functional programming in hindi, java functional programming tutorial, java functional programming example, java java streams advanced, java functional programming with streams, java functional programming interview questions, learn java, imperative programming, declarative programming, declarative programming vs imperative
Id: f5j1TaJlc0w
Channel Id: undefined
Length: 49min 59sec (2999 seconds)
Published: Mon Nov 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.