Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I go for Java-8 Streams?

I've started learning Java-8 streams lately. I'm looking at a huge code base and trying to figure out where can I use streams to improve performance.

From what I've understood, replacing every loop with streams doesn't make sense as streams are not always better than loops. Following are few cases I've understood to be beneficial:

  1. Where only certain elements in a collection results in more computation.
while(iterate over a collection) 
{  
    if(certain condition is met) {  //do some computation  } 
    else { //do nothing       }
}

Using streams here avoids loading the needless members of the collection here. (faster & memory efficient)

  1. when we want to collect results in a collection where the resultant order doesn't matter and each iteration is independent (Stateless). If computation is CPU-intensive and we use parallel streams here, I believe it will be more performant.

Please correct me if I'm wrong. I'm looking for more such cases...

like image 589
A.R.K.S Avatar asked Dec 06 '22 18:12

A.R.K.S


1 Answers

Going back over a codebase and rewriting things by hand is probably a waste of time. Generally speaking, streams aren't going to provide a performance benefit unless you're using parallel streams over a very large computation (see http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html for detailed advice). Most of the time, streams will have ~equal performance; they'll just be shorter to write.

like image 155
Louis Wasserman Avatar answered Dec 08 '22 06:12

Louis Wasserman