Wednesday, December 9, 2015

Transform collection of one object to another using Java 8 Streams

Few days back, I wanted to convert a list of value objects to another list of ORM/entity objects.  It's a very commonly occurring scenario; oh BOY, streams API works like a charm!

If you are working on application having layered or distributed architecture, this scenario is quite common. When data moves from client/UI to get persisted it gets transformed multiple times. Let's see how it can be done effectively in Java 8 using streams API.

public class City {
 private String name;
 private String zipCode;
 //other attribute, setter/getters

public class CityOrm {
 private String name;
 private String zipCode;
 private long id;
 public CityOrm(City city){
  //construct this using City instance
 //other attribute, setter/getters

Please note that CityOrm has a constructor. So transforming or converting a City instance to CityOrm instance is not an issue.  

Problem is:

You have a collection of City; you need to convert it into a collection of CityOrm. 

Before Java 8

 List<City> cities = getItFromSomeWhere();
List<CityOrm> citiesOrm = new ArrayList<>();
for(City city : cities){
citiesOrm.add(new CitiyOrm(city));

Java 8 / Streams API

   List<City> cities = getItFromSomeWhere();
   List<CityOrm> citiesOrm =
          .map(city -> new CityOrm(city))                   .collect(Collectors.toList());

stream() method converts the list of City instances into a stream and then map() method goes through each city and by calling appropriate constructor converts it to another type (i.e. CityOrm). And finally, collect() method converts the stream back to a list. 
So Stream API definitely saved a couple of lines (excuse the spread due to formatting). 

No comments:

Post a Comment