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:


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:


 userRepository.findAll();

Problem:

Find.All() method signature (like many others) returns java.lang.Iterable<T>


      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:

Stream<UserEntity> userEntityStream = StreamSupport.stream(userRepository.findAll().spliterator(), 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:

List<ActiveUserList> activeUserListDTOs =
            userEntities.stream().map(ActiveUserList::new).collect(Collectors.toList());

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:

List<ActiveUserList> activeUserListDTOs=StreamSupport.stream(userRepository.findAll().spliterator(), false).map(ActiveUserList::new).collect(Collectors.toList());

That's neat!!

Idan.

Related Articles:

(20756)

Be Sociable, Share!

2 thoughts on “Mapping your Entities to DTO’s Using Java 8 Lambda expressions

  1. Pingback: Mapping your Entities to DTO’s Using Java 8 Lambda expressions | Dinesh Ram Kali.

  2. Pingback: jesse

Leave a Reply