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

We all facing the cluttered overhead code when we need to convert our DTO’S to Entities(Hibernate Entities, etc..) and backwards.
In my example ill demonstrate how the code getting much shorter with Java 8.
Let’s create the Target DTO:
[code language=”java”]
public class ActiveUserListDTO {
public ActiveUserListDTO() {
public ActiveUserListDTO(UserEntity userEntity) {
this.username = userEntity.getUsername();

A simple find method to retrieve all entities using Spring data JPA API:
[code language=”xml”]
Find.All() method signature (like many others) returns java.lang.Iterable<T>
[code language="xml"]
java.lang.Iterable<T> findAll(java.lang.Iterable<ID> iterable)
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:
[code language=”xml”]
Stream<UserEntity> userEntityStream =, false);
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:
[code language=”xml”]
List<ActiveUserList> activeUserListDTOs =;
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:
[code language=”xml”]
List<ActiveUserList>, false).map(ActiveUserList::new).collect(Collectors.toList());
That’s neat!!

2 Replies to “Mapping your Entities to DTO's Using Java 8 Lambda expressions”

  1. Pingback: jesse

Comments are closed.