Converting Collections With Java Lambdas, Streams and the Collectors Class

An alternative title for this post might be “How to Convert One Collection To Another Collection in Java with 4 Lines of Code.” Using Java Lambdas, Streams and the class really does enable you to convert one collection object to another with very few lines of code as you will soon see.

First let me quickly set the stage. I am importing records from a MySQL database with a Collection called NixMashPost.  We then pass them off to a NixMashupImport Collection from which we will enter them into PostgreSQL.

Here are the properties of NixMashPost.

Here’s the NixMashupImport collection structure we are creating from the NixMashPost collection. Very similar with a few added fields.

Without making you wait longer, here’s the Lambda – Streams – Map – Collectors magic code that converts our incoming NixMashPost collection to a NixMashupImport collection.

In just those few lines of code were are traversing a Java Collection and creating a fully populated, new Collection from it.

.map(NixMashupImport::new) is where the action really happens, and there’s one final piece we need, a NixMashupImport Constructor that receives a NixMashPost object.

Put it all together and you’ve got Freakin’ Awesome Sauce, if I must say so myself.