Video Title: Java 8 Streams API
Let’s start with an example let’s say we have an array of integers called numbers and we want to find the minimum number from this adding one way to do it is we create a variable column in you assign it as a first integer and then you loop
Through the entire array and any number which is smaller assign it to the min again and once we have that minimum we can process it so in this case we are just printing it out to the console with Java eight streams you can achieve the same thing using only a single line of
Code you can say in stream of numbers dot min function this min function though will not actually give you an integer to extract an integer from that min function and to store it in some variable you have to call this method called get as end this get as into
Method can throw an exception when the numbers is an empty array so you have to be careful with using it as it other way to use this main function is to tell it that if you find that minimum if that number is present then perform the following operation and in this case we
Are just getting that in this variable called min and then we are saying that whatever is min you pass it to this function this is a simple lambda which we can replace it with method reference so the same code but you can see system got out colon colon println which is
Nothing but replacing the lambda with the method reference right so very simple you created a stream of numbers you asked it to find the minimum and you’re saying that if that minimum is present if you found it then pass that minimum to this function of system dot out similar to minimum there are
Multiple other functions which you can use to gather statistics of that added so you can say get me the maximum number get me the average of all the numbers get me the count of numbers and get me the sum of all the numbers for a specific array you will have to keep
Calling in stream of numbers again and again to avoid that Java eat in stream also has this function called summary statistics so you can say in stream of numbers not summary statistics this will give you back an object of type in summary statistics the statistics has the functions which will give you all
The same values which we saw earlier which is get men get max average count and some let’s take a slightly more complicated example let’s say there is an array of integers and we want to find the three distinct smallest numbers from it so in this case we want to find 0 1 &
2 one way to do it is we can sort the array and get the first three numbers but if we sort the array we are mutating the original array so what we want to do is we want to first create a copy of that array so that the original is not
Affected and then work on that copy we’ll sort that copy using arrays dot sort and using a symbol for loop we’ll get the first three elements I missed to add the code to find only the distinct elements so imagine if we had 1 extra 0 in this array even then since there are
2 zeros and I want only distinct numbers I would still expect it to give 0 1 & 2 right so to find those distinct we’ll still have to add three or four lines of extra code but if we are using Java eight in stream we can do it in a much more
Simpler manner we can say in stream of numbers you get me only the distinct numbers sort them using this method called sorted and limited to the count of three and for each of these three elements you perform this method and the method is just printing out to the
Console so this is much more elegant than the code that we saw earlier even though you’re calling the sorted method on the in stream of numbers the original array is not mutated it internally creates a copy of that array and then works on that copy it will not mutate
The original Alec and after doing these intermediate operations of distinct or sorted or limit you can again call the same method which we saw earlier which is some average count min and Max we have three distinct parts to using a stream create process and consume the same example as
Before the first line we are creating the stream the next three methods we are sort of filtering we are applying our logic or algorithm or process with that stream yes by calling distinct sorted and limit and the in the end we are using that processed stream to extract the values
And do something with the values and that part is consumption of the stream visually it looks something like this so we have an array of 1 4 0 1 and 13 we are saying create it into a stream it will create a stream of elements we are
Applying distant so it will only allow the distinct elements to pass through so in this case there are two ones so it’ll allow only a single one to pass through this filter so we have 4 0 1 and 30 now we are calling sort it will come out in
A sorted manner so you will get 0 1 4 and 13 and then we are saying limit it to 3 in this case it will limit it it will allow only the first three elements to go through and it will block the remaining ones allow only 0 1 & 4 and
Then we have the final terminal operation which in this case is sum which will give you the sum of the elements that it received and from limit it received only 3 elements so it will give you the sum of those 3 elements which is fine first part is creating the
Stream the second part is processing that stream using transformations or filtering and the last part is consumption on that stream there are other ways to create an in-stream we already saw creating the in-stream offered up an array you can create an in-stream out of hard-coded values or
You can create a stream from your custom method for processing we already saw a few methods of these you can say give me only the distinct numbers sort the numbers you can say pick only the first few numbers an opposite of that is you can skip a first few number
You can give your own custom logic to filter only allow elements which pass this filter and in this case we are saying that if that number person to equal to equal to zero which means that the number is even only allow those numbers to pass through the next one is
Mapped which we can given the number it can convert it into a some other number so in this case it’s doubling the number and it also has this method called boxed which will convert the primitive numbers into rapper integers and the third part for in-stream which is the consumption
Part you have already seen the statistics of min max and so on and so forth we can also see for each of the elements that you find do some operation we saw this earlier if you do not want to do an operation right away but you
Want to collect it you can do it in an array you can just say to array it will collect all those numbers into an array and if it is boxed which means it’s an stream of objects which we’ll talk about later you can convert it into a list
Also there are two special methods which will return only a boolean true or false and those methods are any match and all match as the name suggests any match will return true if any of the numbers in the string pass this criteria so in this case the criteria is number % 2
Equal to equal to 1 which is if any of the numbers in the stream is an odd number then return true else return false all match ensures that all the numbers will have to pass this criteria if all the numbers in a stream are odd then it will return true otherwise it
Will return false so until now we saw in streams but the beauty of streams is it works with objects also so let’s start with an example let’s say we have a list of employees and we want to find the names of three highest earning employees again like before we don’t want to salt
An original list so that’s why I will create a copy of that list call the sort method for that list and in this case we want the highest employ highest-earning employees and that is why I will sort it in a reverse way so in the sword we are giving it the
Comparator function we are saying compare Oh to salary with the o1 salary and then sort it accordingly once the list is sorted then we’ll find the first three employees from that sorted list and we’ll print the name of the employees to the console to do this
In using a stream it’s much simpler we can say employees don’t stream not sorted very similar to the in-stream we saw earlier but here it is not integers so it doesn’t know how to sort our values and that is why we can tell it that please sort according to this
Comparator sorted comparing the integers which are represented by these salaries so you call employee : : get salary for two employees compare those as integers and compare it in a reverse manner because we want it to be sorted in the descending order and then you want to
Limit it to three because we only want three highest earning employees and then we do not want the employee object we want to get the names of the employee and that’s why we can say map which will map the employee to employee not get name and then for each of these three
Names we can say for each call this function again compared to the previous code this one is lot easier to read and understand so the same requirement as before three highest earning employees but this time we want to ensure that the employees aren’t still active in the
Form okay so let’s say there is a method called is active and it will return you true or false based on whether that employee is still active yes so adding just that single extra parameter in the requirement increase the size of the code and now this code is not readable
Anymore but with streams you can have the exact code as you had before and you just add a filter in the filter you can say that given an employee check if the employee is still active and the rest of the code remains the same here instead
Of doing for each we can also do not collect you can collect those names into a list a list of string which you can store in this variable called names again much more elegant than the previous score stream sorted you filter it whether the employee is active or not get the first
Three employees extract their names and then collect those names into a list and like in stream object stream also worked in a similar manner so in this case we have a stream of objects let’s say the objects are shapes so we have some square shapes we have some circles they
Have certain color and the number represents their weight we can call the filter method where we say ensure that the shape is a circle so in that stream this filter method will only allow the circles to go through it is lock all the squares you can again apply a filter you
Can say that only allow blue so it will only allow the blue circles to go forward it will block the remaining ones you can say sort by weight so it will change the order of the stream it will give you an assorted order of their
Weights and then you can map it so you can say given a shape extract the weight of their shapes so now you just have a stream of numbers once you have that stream you can collect it into a set and we’ll give you a set as an output yes so
It’s incomplete pipeline or an algorithm that you can write in a very elegant manner using streams and streams are made extra-special because of this concept of collectors so we saw that in in-stream we can use men max average and those terminal operations but in object streams we can do something extra so we
Already saw that we can collect the stream elements into a list we can also collect them into a set you can say collectors dot to set and you can also collect it into a map so you can say collectors dot to map where the T is e
Dot get name and the value is e itself there is also a collector called joining so in the earlier example where you extracted the name of the employees you can just say give me as a string join all these strings using this delimiter which is comma separated values and give
You this output so if you have three employees named John Amy and Massey I’ll give you a string John comma Amy comma Marcie you can group a stream so in the same example of employees you can group all the employees by the department all you have to say is collectors dot group by
Employed on department sale then give you a map of the department and for each department will give you a list of employees you can even say give me the count of employees in each department group by employees department and then there is this collector called counting
Which will just keep a count and the last concept is about having parallel streams so all these streams are generally done sequentially by a single thread but if your stream is too large if your input list or your input array is too large you can also use parallel
So you can use employees dot parallel stream or you can do employ start stream dot parallel that is also the same thing it has to distribute the work internally and aggregate all the values or the final terminal operations together and that is actually a performance hit so
The advantage of using parallel is only apparent when you have huge number of elements in your stream so typically from what I’ve read if you have more than 10,000 elements then consider using parallel streams but even then it’s better to measure the amount of time it’s taking amount of memory it’s
Consuming and then decide whether you really need a paddle steamer and the last caveat that I want to cover is of course when you are using a stream on a list or an array and when that operation is being performed by a thread we should avoid trying to modify that source that
Array or a list in some other thread yes so you have to provide the thread safety in your own source some concurrent version of lists and arrays or the some streams that you are using so that’s it about streams quite elegant and quite powerful to use thanks a lot
For watching and see you in the next one bye
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Thanks for video.. is stream are faster than old for loop ? if yes why?
FIY: the logic for the first example "The old way" is not quite right it's finding the max instead of min the operator should be ">" instead of "<"
🙏👍👍
👍
Great video
Great, Thank you 😘😘😘😘😘😘😘
I checked ur channel quiet late , but ur all videos are awesome ,easy to understand and explanation is far better than other channel , thanks
excellent video, kudos
Awesome
Really amazing…
Thanks for the video, small correction find the min number in an older way, the if condition was wrong (if (number[i] < min))
Respect ++ Sir !
Very clear explanation . Useful for interviews 😊😊. Thanks,🙏🙏🙏
This is the best and crisp video on Streams.. covered so much in short time and your audio is also soothing to listen , Thank you for all your hard-work 🙏🙏🙏
One word Excellent!
Will the order of intermediate operations matter for stream to optimize them ?
Very clear explanation, thanks for your effort.
Thanks for this golden content
Great video, but I have a question about IntStream.of(1, 100).boxed().collect(Collectors.toList()); // collect into list
Why didn't the following lines work?
LinkedList<Integer> linked_List = IntStream.of(1, 100).boxed().collect(Collectors.toList()); // Does not compile.
ArrayList<Integer> array_List = IntStream.of(1, 100).boxed().collect(Collectors.toList()); // Won't compile either….why not?
Thanks, I appreciate your help.
Seedhi baat no bakwas..
I do not know if this was done on purpose, but there is a mistake on the first piece of code: You want if ( min > numbers[ i ] ) at 0:10 . Otherwise, you would be calculating the maximal value.
But this actually shows a useful aspect of Java Streams: less mistakes while writing trivial code.
Outstanding !!!!! the best video on streams I came across.
You are the best…awesome explanation with great examples. Thank you, Keep going.👍
I have a question, suppose we have an array arr = {1, 5 ,10}; i want to check odd and even and return a string through steam API like "1o5o10e", for every odd add o and for every even number add e, How can be possible this, please.
Hi, Can you please share the slides as well?
Nice explanation
finding min value condition is wrong (replace "for (int i = 1; i < numbers.length; i++) {
if(min>numbers[i]) {
min=numbers[i];
}
}")
Good explanation 🤗
Best for revision of java stream api
package hackerRank;
import java.util.Arrays;
import java.util.Scanner;
import java.math.*;
public class Subarray_Division {
public static void main(String[] args) {
int n,i,j,sum=0,k=0;
Scanner scan = new Scanner(System.in);
n= scan.nextInt();
int[] s = new int[n];
for( i=0;i<n;i++){
s[i]=scan.nextInt();
}
int d = scan.nextInt();
int m = scan.nextInt();
for(i=0;i<n;i++){
sum=0;
for(j=0;j<m;j++){
sum= sum+s[i+j];}
if(sum==d)
k++;
}
System.out.println(k);
}
}
//"can any one tell me why this code is throw Exception.. and what will be the correction in this code"
Great tutorial. Thank you so much!
This video is very interesting. Although!
The old code to find out the minimum element from the array
The "if" condition is wrong.
it's < if ( min < numbers[i] ) >
the expected should be < if ( min > numbers[i] ) >
the code in your video will give you the maximum number.