Idan Fridman

About Idan Fridman

Idan is Software engineer with experience in Server side technologies. Idan is responsible for various infrastructure models in the software industry(Telecommunications, Finance).

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 is 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>
1

      java.lang.Iterable<T> findAll(java.lang.Iterable<ID> iterable)

We can’t 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’ve 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:

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You'll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You'll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

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

  1. Yannick Majoros says:

    A DTO shouldn’t know about the entities it maps to. “Conversion” should be made elsewhere to avoid coupling them.

    BTW, I hope you think twice because having all entities duplicated as “DTO’s”. Is it needed in your use case? I saw too much projects where this was done blindly without added value.

Leave a Reply


9 × five =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books