[JAVA 8] Custom DTO mapping

Very nice idea:


Mapping your Entities to DTO’s Using Java 8 Lambda expressions

In my example ill demonstrate how the code getting much shorter with Java 8.

Let’s create the Target DTO:

A simple find method to retrieve all entities using Spring data JPA API:

We cant make a Stream out of java.lang.Iterable (* Streams working on collections. Every Collection is Iterable but not every Iterable is necessary a collection)

So how do we get a Stream object in order to get Java8 Lambda’s Power?

Let’s use StreamSupport object to convert Iterable into Stream:

great. Now we got Stream in our hands which is the key to our Java 8 labmda’s!.

What’s left is to map and collect:

I am using Java 8 Method Reference and therefor initiating (and mapping) each entity into dto.

So let’s make one short line out of everything:

That’s neat!!



Leave a Reply

Your email address will not be published. Required fields are marked *