How we should use a streams?

Do you think sometimes about how we should do something? I was that moment with streams. Maybe my post learns you about streams.

My first contact

The first time when I heard about streams, I thought this was the same as Apache collection library and abstract class. A lot of time this was for me the same. Why? Because I didn't know about how it work and for how case it is created. 

What difference is on stream?

Stream executes all operations only at the end of the pipeline. Find, match and collect are terminating operations. It's close our pipeline, execute operations and return result. When we implement the same without a stream, we execute each by each operation in the implementation place.

Fun fact

I heard that stream is faster than a loop. I don't know who give him that information, but it is crap. My tests show that the time of each way is close. Article on other side show you that the stream is slower.

When stream uses?

I like stream. It is very readable, so I don't think that place exists where using it is bad. I prepare tests for You which show you operations times. The result of it shows us the time is close to each other.

Take a look at ComplexWithoutCollectOnlyTimeTest.

In this test times is very different. Why? Because in this specific case we use a feature of a stream. We don't execute any operations on data, so we don't lose a time. This is only the way when I found time optimization on stream.

Followed this thought how we should use the streams?

I have three places when we should use it. The first is a place where we return the collection. We don't know how other programmer want use this collection. Maybe it wants only findFirst or matchAny. Maybe it wants filter it and sort before these actions. We don't know, so this is a good place for a stream. The second place is when we want do any operations on collections. It is more readable than Apache CollectionsUtils and other library. We should only remember about close stream, so we don't give that collection to another function. The third place is getting a stream as parameter. I saw a lot of places where we put the list parameter for the function, but we don't use it because the conditions were not met. This is the way where we can save time.

Summary

The stream is a good feature, because a lot of places in our code are more readable. As you know it is very helpful for us. We can save application time use it as parameter. Sometimes we reduce execution of filters or sort operations. You can take a look on my test code where I use stream.

Comments

Popular posts from this blog

Why TDD is bad practice?

How correctly imitate dependencies?

Software development using Angular 5 with Spring Boot