So I posted last time about filtering Java Collections using a "functional" approach. Today I'll look at another useful operation - transformation.
This is slightly more complicated than filtering, but not much. The problem this time is to take a List of Object's of some Type, and transform it into a List of Object's of a different Type. For example, convert a List of ReallyComplexObject's to a List of EquallyComplexObject's:
Of course there are many alternative ways to write this. Not least you should factor out the creation of the EquallyComplexObject to a separate method that would be invoked in the for loop. I took a similar approach with transformation that I used for filtering, and arrived at:
Again, the expressiveness of this really shines when you factor the Transformer out into a separate class, or create it in a separate method. Our client code becomes:
To support this the Util class gets a few extra bits and pieces:
Its turned out to be surprisingly useful - i'm already using it in lots of places and finding the results pleasingly readable. The biggest gain, to my mind, is that you get to code at a higher level of abstraction because in each case you don't have to think about the mechanics of iterating the original List's.
Yes I know its ridiculously simple to iterate a for loop, and where the predicate or transformation is simple the alternative presented here appears to have dubious value, but somehow making a "Filter" or a "Transformer" that focuses on how to filter or transform just one object is ... well, its transformative. Try it, you might like it :)
No comments:
Post a Comment