Streams API Tutorial in Java 8+

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up everyone and welcome to daily code buffer in this video we are going to learn about the streams api of java 8. stream api was introduced in java 8 and after that it has changed the course of how we do the java development it has changed the complete imperative style of programming into the functional style of programming so in this video we are going to learn about how we can utilize stream api and how it is useful to use the stream api rather than traditional for loops and all those imperative style of coding so without any further ado let's get started [Music] so let me just start the project over here in intellij idea i'll just open the intellij idea here and here i'll create the new project i'll just name stream api tutorial and i'll just give the name as group name as com dot daily code buffer and package name as stream api such as the basic details nothing else i'll just generate the basic project of spring boot you can create a basic java project as well basically on project as well just to understand what is stream api it is this is quick so i'm just creating this project so we'll wait until the project is ready let it load everything and here you can see that this is your project this is your main file you have your main method here and here what we will do we will go to the bunch of methods available in the stream api that you can utilize and how to get our desired outputs so what we will do we will work on a list of object over here so the object i am going to create is the employee employee will have a bunch of fields and will create a list of employees and we will be doing the operations on top of that list so first let me just create the class over here employee class and let me just add a few fields here i'll just add private first name private string last name private double salary and private list of string projects which projects they are working on my employees okay so these are the fields now let's create the catastrophes i'll just create the data setters for everything and i'll create the constructor with no arguments and i'll create a constructor with all the fields as well and i'll create one two string method as well with all the fields okay so my basic pojo is created of employee now i can list down all the employees i can get the data from the database or in this particular example we will just hard code everything to have a list and we will do operation on that using the stream api so let me just go to the stream api tutorial application.java where our main class is and here i will define static list of employee employees equals to new error list okay and in the static block let me add all the employees so what i'll do i'll add employees dot add new employee and i'll just give the name subway daodhi suppose the salary is 5000 rupees in double and then i'll add the project so i'll just add list dot off project one comma project two okay one employee is added let me just add the another employee as well employee dot and here i'll just change the name i'll just add nikhil gupta and here i'll add shivam kumar and here i'll change the salary from 5000 to 6000 and here 5000 to 5500 i'll change the project details project 1 project 3 and here project 3 and four okay so you can see that we have an object list of objects which have a different types of values available we have the strings for first name last name we have a double salary and we have a list of string as well within the object let me just correct it here shivam and here i'll just change comma okay generally this type of object you will be working in the real application where you will have a bunch of different collections and bunch of different data types available for your object and you need to do some operations on it ideally what you will be doing in the imperative style of programming is you will be running through a for loop or a while loop or a while loop and you will be doing some operations on it but with streams api you can do even much better stream api consists of different methods available those methods either would be terminal methods or terminal operations or it would be intermediate operations those operations you can do on a collection that you have and based on that collection you will get a desired output whatever the output you want you can get the output back from the stream and it is also lazy in nature so until and unless a terminal operation has been called the other intermediate operation won't be executed until they need the proper data so it would be much faster in implementation rather than your imperative style of coding so let's start with the examples and let's see what all things that we can do so yeah let me just comment it out here and to create a stream of object what you have to do is you have to use the stream interface okay and if you do stream dot off and you can pass the collections or values here if i'm passing employees then i'll be getting the stream of employees stream of list of employees here directly okay and if i print it i'll get the object here so this is how you will be able to create the stream using the stream interface but ideally what we'll be doing is we will be calling the stream method on the collection itself so that also will be able to convert to the stream so rather than doing stream note of employees we can also do employees dot stream so this is also we will be getting the same result so what we did is we are changing our collection to the stream stream is nothing but it gives us the abstraction to work on it is not now a collection object it's now a stream object whatever operations that we are going to do those all operations will be on the stream and at the end whatever the collection or whatever the data type you want you can get the data back so the most basic thing you would be doing is using the for loop using looping through all the elements so let's do that first i'll just define for each year so what we will do for employees.stream we'll be doing for each okay now forage is a terminal operation so so once you do the 4h you cannot do any operation after that now for it you can see that it takes a consumer so it's going to consume any data and it will do some operation on it so you can see that we have to use the lambda expression over here so for each of the employees we have that is a list of employees it will take each element as the input so you can see it will take employee year and for that employee we can do any operation suppose if i am doing just printing out here okay so i'm taking i'm taking the employees here that employees is converted to stream for each element in a stream using the forage loop it will take each employee and i'm doing any operation over here simple things simple for each if i run this you can see that i'm getting all the three objects that is shabby nickel and shivam cool okay now let's add any intermediate operations on it so the basic intermediate operation that you would be doing within the stream is using the map so what map does is it allows you to map a particular object into a different type of object and it will return the stream at the end so let's take the example of map here so what i'm going to do here is i am doing employees dot stream and here after that i am doing the map operation okay map will take one object and it will give the another object to you whatever the mapping yet you want to do so what i want to do here is i want all the employees here whatever the employees and for each and every employee that has been given to me using the map for that for those all employees i want to increment the salary by 10 percent okay so at the end i'll be getting the employee back but the salary component will be changed to increase by 10 okay so what i'm going to do here i'm getting the employee and for that employee i am creating the new employee object and for this i am getting employee dot first name employee.lastname employee.getsalary into 1.10 so i am increasing the salary by 10 percent here then employee dot get projects so you can see that i converted into map but if i just end this operation here it will be just giving me the streams but at the end i don't want streams i want the data back into any of the collections so this time you can use the collect method so let me just comment here that we are going to use the collect as well so what i am doing is after this operation after this map is completed we are doing the chain of operations so after this again we can do chaining of operations and i can do collect what i want to collect i want to collect this data into the list back so here you can see that this is the method that is taking the collect and collectors dot to list it is doing so the entire streams it is going to collect back into the list and here i can take the list of employee back list of employees i can say increased salary okay so what i did i took the employees and i streamed through it and then i did the map operation that's the intermediate operation i took each and every employee and i created a new object for each new object i just incremented the salary to 1.10 that is 10 and then at the end after this operation is completed i am collecting back all the data to the list okay and then i can do s out increase salary and if i just print this you can see that everyone's salary has been increased you can see that earlier it was five thousand now it is 5500 and so on for nikki right 6600 and for shiva met is 60 50. now the other thing you can do is you can take this data into set as well now if you don't want into list you can convert it to two set and you will get the data into set and here i can change to set okay so collectors you can use this way as well in whatever radiator drive you want you can get the data back now let's check one more operation that is the filter operation filter operation is nothing but you will do if else loop to filter out some of the data right so that we can do using the filter operation so what we can do here here in the previous example we incremented the salary of each and every employee but now what i want to do is i want to increase the salary of the employee whose salary is greater than 5000 okay so i want a filter operation on that so simple i'll do of employees dot stream dot filter operation here you can see that filter is taking a predicate so it will be executed based on the true or false value okay again it's a lambda expression always so we'll be taking the employee and we will check the employee dot get salary should be greater than 5000 okay if any employees salary is greater than 5000 those only will be pass through it and the next operation will be performed on it and then again once that is done i want to do the map operation you can see that filter is also the intermediate operation map is also the intermediate operation now how you will get to know that which is intermediate operation any any operation that is retaining the stream itself that's the intermediate operation okay so filter is also returning the stream object you can see that it is returning the stream and map is also returning the stream okay so here we will do the map operation again and map operation you will do the same thing so i'll just copy this okay and here you can see that we are adding the chain of operation like what all operations that we want to do and after that i want to collect the data back to the list you can see it's simple now if i get the list of employee here enter employee and if i just print this you can see that i got two results only that is nikhil nikkilan shivam only two should be reason order because it's salary is 5000 we want only salary is greater than 5000 so you can see this way you can add the chain of operations and how the filter is working within this filter we will add one more operation that is the find first now what find first will do is it will get the first element out of it now rather than doing this collect let me just copy this so it's better so this operation we did here okay and i'll just change to first employee now rather than taking all the data into collect all the employees what i want is i want the employee i want the first employee whose i have increased the salary so after the and find first is the terminal operation so after the map operation that i have done i want to get the first employee so i can just do find first and here you can see that find first returns the optional optional of employee now option is something that requires its own video but what option will do is it will optionally send the value it might have the value as well it might have the employee object as well or it might not have the object as well anything can happen so it's returning that optional so for this option we have to check that also like if there is a value within that optional that's fine if there is no value within that option i want to do some other operation i want to throw an exception or i want to get the any dummy value or i want to get null so here what i'll do i'll just define that find first is optional if there is no value then or else i can define or else pass null okay and here this will be the employee not the list because we are just getting one value okay so if i print this as our first employee you can see that i'm getting only nikhil gupta okay only one you can see only one is there now if i change this value like i want all the employees greater than 7000 then at that time this rls will be executed and i would be getting null you can see that i am getting null object here okay so this way the optional will be written and you can use or else or else get or else through method to do any operation that you desire now let's see another operation that is the flatmap operation flatmap operation is nothing but to flatten up the object that you have suppose you have the list of string and if you do the flatmap operation you will get a stream of strings only you won't get a stream of list of string if you have a list of list of strings you will get a list of strings so one data type that you have that is containing it it will just flatten out that particular data type let's see that in example so what i want is i want employees so what i'm trying to do is i'm trying to get all the projects that i have right so all the employees have a list of projects within that particular object but i what i want is i want that entire list directly okay direct strings directly i want so what i will do is employees dot stream then what i'll do i'll just map everything and what i want is i don't want the entire object i want just a list so from that entire employee object i'm just getting the employee dot get projects so at this particular point this line number 87 you will be having the stream of list of employees but after this map operation you will be having the stream of list of projects okay because we mapped our employee object to the list of projects then i am doing flatmap operation here what flatmap operation is happening is all the strings that i have right that i want to convert to strings dot stream okay so here the list of strings will be converted to just strings and then i am going to collect all those values dot collect you can either collect in the list as well but what i want i want to collect in a string so what i'll do i'll do collectors dot joining and i want to join all those values by comma okay so here i want to do is stream this entire list of employee object is now converted to these string that have the list of projects so here i can take string projects equals to employee.stream and here you can see that you are seeing everything at this particular time it was stream of employee after this map operation it converted to stream of list of string after the flat mob operation it converted to stream of string and then we are collecting all the strings separated by the comma operator okay and if i do s out here and just print projects i'll be getting all the projects separated out by comma so here you can see that i am getting all the projects separated out by comma cool right now there are short circuiting operators as well available so what short circuiting operators will do is it will limit your data okay so let's see that so let's just define short circuit operators short circuit operations and here what we will do is let me just grab the employee lists and then if i stream through it now what i want to do is i don't want to do any operation on the first element okay so i can just skip that element skip one so the first element would be skipped so you can see that we are just short circuiting it for first one don't do anything okay and then what we are doing is we are also adding the limit limit to only one so that means skip one then take the one means whatever the limit that we are setting it and then rest of the elements are skipped directly okay then collect all the elements you can see it's very simple let me just grab the list of employees here again this is a list of employees and i can just say short circuit okay and if i just print out and run this you can see that i'm getting only one employee that is the nickel okay no other employees so you can see that we short circuited the data we just bypassed the first element and we took only one element out of it okay now the next thing that we can do is see we can look through the finite data okay suppose you have a list of data that is infinite and if you want to convert to finite data that also you can do using the limit itself directly so what you are doing is if you have stream dot generate i'm just generating the random value let me just do math random okay i'm just generating the random value over here and it will just loop through okay so what i want is i want to limit to only five okay so it's converting my entire loop to only five elements here and then what i want to do is for each of those elements for each of those elements i want to do s out okay so you are just converting your infinite data to this finite number of data and if i run through i should get the result back you can see that i'm getting five records over here okay so converting to finite data as well so this is all operations that you can do the next operation you can do is sorting as well so always when you do sorting you will need to use your comparators or comparable that you can use within the stream as well so let me just define sorting and let's see sorting so what i want to do is i want to sort my list based on the first name itself so i'll just define employees dot stream dot sorted and here you can see that this sorted is taking the comparator so within this sorted let's take the comparator it will take the two values and it's a lambda function so we'll just define one dot get first name dot compares to ignore case go to dot get first name okay so this is just a sorted operation that we did and after that once you do the sorting if you want to collect you can get the data collected back to your list okay you can see whatever we are doing till now all its chaining operations and either we are doing the intermediate operation and at the end we are doing the terminal operations to get the data back and once this is done i can take to the list of employee sorted employees equals to this and if i just print this value to sorted employees i'll be getting all the employees which are sorted by the name so first is nikhil then shabbir and then shivam right all the values are sorted according to the comparator that we have provided here now the next thing that we can do is we if you want to get the minimum or maximum number of data or the minimum or maximum value that also we can get based on the stream so suppose i want the maximum salary out okay who has the maximum salary that we can get using the max operator if you want minimum you can use using the minimum operator so what i am doing here i am looking through the employees.stream again and then i am doing the max so you can see max is taking a function that function needs to be executed based on that we are going to get the data so within this max function what i am doing i am doing comparator dot comparing okay if you want any comparator you can use the comparator and you can see comparing is again taking a function what i am comparing based on is employees salary okay and this should be max not map okay and this will again get you the optional you can see that it will give you the optional so as earlier we saw the optional we can at that time what we did was we did the or get so we took the other value but now suppose if that value is not present i want to throw the exception so i can throw exception as well or else throw and here i can define no such element exception new okay so this will give me the maximum salary who have based on the salary that is provided in the object if there is no object available it will throw the exception simple okay so this way you can get the min or max as well now the next one is the reduce now reduce is something to convert or to accumulate everything suppose you have the entire list and you want to accumulate every data suppose each and every list in our case employees employees have the salary okay all the objects of employees have the salary and if i want to accumulate each and every salary to a total or to a multiplication or to any value that is something that i want to accumulate that type of thing i can do using the reduce function so let me just give you the example like all the salaries are been accumulated to some so i can just simply define all the employees i have stream through all the employees and do the map operation and what i want here is rather than the entire employee object i want just the salaries of the employee so i'll just take the employee here and i'll just pass employee dot get salary okay so now when i do the reduce operation i'll be only working with the salary part not the entire object now reduce will take two things one is will be the accumulator value that is the initial value so i'll just pass 0.0 that is the initial value and after that it will take the binary operator what we want to do so we want to sum up everything so i'll just define double of sum okay summation every values that you are getting okay and here i can just define double total salary and if i print the total salary i'll be getting all the total salary of the employee you can see that i'm getting 16 500 that is the total salary of five thousand six thousand and five thousand five hundred so you can see that we see a lot of operators these are the general operators that you'll be using day to day when you are walking with the streams there are a lot more other operators as well if you just go to stream dot you will get a list of operators you can see that you have map reduce filter skip limit reduce and you can see all those will be taking a different types of input parameter you can go through and you can learn all those things it's very easy to implement once you get the understanding how to write your functional code it's very easy to implement it okay you can see that there are a lot of methods available and all those methods have a proper documentation as well so you can follow along you just have to remember that whatever you were doing earlier like in the imperative style of coding that's completely different than what you will be doing in the functional code at the first it will be difficult for you to understand what you are doing it will be trickier as well to implement at the first but once you practice it once you start implementing with this after a few days you will get more understanding on it and you will be always go with streams rather than going with the imperative style of coding now if you want to do any parallel operations on it rather than sequential operation you can convert your stream into parallel if you just convert to parallel stream your entire stream will be converted into parallel operations now once you do this you need to make sure that whatever operation that you are doing those are thread safe and all the thread safety on all the threads checks that you have to do in your application that you are doing okay but if you have the need you can do the parallel stream as well now the other advantage you will get using this stream is the lazy implementation so until and unless the data is being needed by the operators the operators won't call those functions so suppose if i take this example suppose okay this short circuiting example so what it is doing is it just converted converted to stream so suppose you have three elements after that it skip that element so first is skip and then you are doing limit so you can see all these operations are not going to perform until and unless this terminal operation has been called okay and this terminal operation is being called for the data that you have left off so suppose this keep operator is there right so it's keeping first operator and this limit operator will only get the limited data that has been performed by the first operator operator so suppose if you are doing filter operation and if you have thousand records and filter is returning you only 20 records so the next operator will only work on those 20 records itself it's not going to again work on all the 1000 records if you do imperative style of programming that's what you will be doing in your for loop right you will look through each and everything and either if you want to do that kind of thing as well if you want to just leave it down to only 20 you can do it using the break and continue everything but there's more cleaner way and is what you will understand easily once you go through the code as well so just go through stream api just start using it it's very easy to implement once you get a hang of it so in the starting i'm sure it will be difficult for you to implement it was very difficult for me to start implementing because every time you have to go through stack overflow or google to how to do this how to do this that's fine that's the initial step you have to do so that's what i wanted to say regarding stream api just go through it if you have any doubt do let me know in the comment section below i will try to help you out as soon as possible if you like this video give us a thumbs up and subscribe to my channel for the upcoming videos you can also join my channel and support me as well and if you are interested in learning spring boot and micro services then these are the videos that you can check that out i will see you in the next video till then happy coding bye [Music]
Info
Channel: Daily Code Buffer
Views: 53,810
Rating: undefined out of 5
Keywords: streams, java, java 8, lambda, map, reduce, filter, sort, collect, tutorial, pipeline, functional, programming, how to, explained, stream processing, java 8 streams, stream api interview questions, stream java, parallel stream in java, java functional programming, map reduce, predicate, how to use java streams, how to use java collections, java tutorial, java streams, java streams tutorial, java streams advanced, stream api, stream api in java 8, functional interface, java 8 stream
Id: VNovNwHr9jY
Channel Id: undefined
Length: 31min 38sec (1898 seconds)
Published: Sat Apr 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.