Intro to Java Streams

Question #1.) What are Java Streams ?

Note: We are not responsible for performing the iteration.

Question #2.) Convert the below code to the Streams :

Solution → In the above code-piece, we are running a for loop and performing the business logic. The equivalent Streams code for the same shall be :-

Question #3.) Detail some important functions of Streams ?

Answer :- Following are the important functions available with Streams :-

Some examples with Stream of Numbers :-

Question #1.) Given the following stream of numbers :-

Here, our task is to print all the numbers into this stream ?

Answer :- This is how, we shall be able to print all the numbers :-

Approach no. 1 → Using the number to print the same. This approach is more obvious and easy to read :-

Approach no. 2 → Using the method reference :-

Question #2.) Given the following stream of numbers :-

Here, our task is to print only those numbers, which are lesser than 5 ?

Answer :- This is how, we shall be able to print all the numbers :-

Note that, we have used the proper naming convention in the above code-piece. We can use any other naming-convention as shown below :-

Question #3.) Given the following stream of numbers :-

Here, our task is to print the second and third numbers, which are greater than 5 ?

Answer :- This is how, we shall be able to print all the numbers :-

Question #4.) Given the following stream of numbers :-

Here, our task is to print the first number, which is greater than 5 and If nothing is found, then we end up printing -1 ?

Answer :- This is how, we shall be able to print all the numbers :-

The advantages with this type of coding with Streams are :-

Some examples with Stream of Objects :-

Question #1.) Given the following stream of Objects :-

Here, our task is to print the first name of all the users in the above stream.

Answer :- This is how, we shall be able to print all the required values:-

Note here that, map function replaces the value in the stream with the new value.

Question #2.) Given the following streams :-

Here, our task is to print the first name of all the users from the userStream, for users that have IDs from the numberStream.

Answer :- This task is little complex, because we gotta join multiple streams here :-

Thanks for reading through this blog. If you liked it, do clap on this page. We shall see you in next blog in this series.

--

--

Software Engineer for Big Data distributed systems

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store