More power through JAVA streams
We know how the very concept of collections is wedlocked with the test automation and how important it is to understand the deeper aspects of JAVA collections and use the right data structure.
Having said this, working with collections isn't always ideal especially when we have all the required power to derive things in a more efficient way.
When processing our data using JAVA collections, we are forced to write a boilerplate code with multiple nested control flow statements — Using streams, we can avoid multiple lines of code and acquire the same result in a much efficient way
A stream is a conceptually fixed data structure whose elements are extracted on demand.
If we have to understand this in a simplistic view, it is a lazily composed collection. Values are enumerated as they are requested by the consumer.
A simple code snippet to see the visual disparity between processing a collection the old way versus the JAVA streams
With collections, we iterate the collection externally processing each item one at a time. Where as with streams, the processing is totally internal and therefore referred as internal iteration
A simple metaphor to understand the internal iteration better —
wife: we are running out on provisions, can you please go get them from the market..
me: sure thing..
wife: call me on the way back
me: hey, I’ve got vegetables, milk and all the required provisions.. I am on my way back home
wife: can you get some onions and garlic as well please
me: sure..
wife: calls me back again and gives a fresh list of things to get from a different place..
This is what we literally do with collections, we iterate over a collection externally, explicitly pulling out and processing the items one by one.
Instead it is efficient and easy if she tells me what exactly we need in the first place. May be I can find a store, which has all the required items or buy them in a different order, which is more optimized ( of course you cannot keep a competent man down — but it would have been a much easier job :))
We will expand on this very understanding in the future blogs as we go along..
About me: I’m working as a software test consultant who cares for helping employers enhance and simplify their testing efforts through smart application of tools.