After streams being introduced in a major release most of the operations on collections are eased also at the same time its bit tricky and confusing sometimes, I have taken some examples to discuss some of the common problems we face while developing. Problem solving streams Java Collections
Problem 1 – Action on every item of a collection
Suppose you have a List of integers and you are asked to add a certain number to it and store the updated list.
Refer to the attached figure you can easily make use of forEach() operation which is very similar to the traditional for loop and has same complexity just the additional variable declaration is eliminated in this pattern.
Problem 2 – Average on the collections
With the help of streams its quite straight forward that we directly make use of the inbuilt methods to do average. This in turn eliminates the two step process that was taught to us where we first added all the numbers and then divided it with the total number of entries.
Problem 3 – Filtering the entries
It’s a very huge topic al together still I have taken very basic example to show how the filter operation can be used to select the entries on the given condition.
Here in our example, we are only selecting the entries which are greater than 20 using filter which is one of the most popular method of streams.
Pro Tip: Sometimes you may have to memorize the pattern because you may not have the facility to use IDE in interviews.
Problem solving streams Java Collections