Strategies for converting collections from one type to another

What is the most efficient way to convert ArrayLists from EO (Entity Object) to ArrayLists of DTO objects or ArrayLists identifiers. Please keep in mind that each EO can consist of properties that are also PRs or collections of PRs that must be internally converted to DTO or omitted (depending on the conversion strategy). In general, a lot of templates.

wish it was so simple:

collectionOfUsers.toArrayList<UserDTO>(); 

or..

 collectionOfUsers.toArrayList<IEntity>(); // has only an id, therefore it will be converted // into a collection of objects, having only an id. 

Of course, this can also be nice:

 collectionOfUsers.toArrayList<Long>() // does the same thing, returns only a bunch of ids 

Of course, someone should adhere to matching strategies, such as Factory or sth.

any suggestions?

+4
source share
3 answers

You can simply use the simple interface to simulate the conversion.

 interface DTOConvertor<X,Y> { X toDTO(Y y); } public static List<X> convertToDTO(Collection<Y> ys, DTOConvertor<X,Y> c) { List<X> r = new ArrayList<X>(x.size()); for (Y y : ys) { r.add(c.toDTO(y)); } return y; } 

Note that this is just like a library that implements map functionality.

In terms of efficiency, I think you will run into problems because objects of objects will (possibly) be retrieved from the database. You could look forward to finding out if that matters.

+2
source

You should create a general method for converting from one type to another. Here is a simple interface for this:

 public interface XFormer<T,U> { public T xform(U item); } 

Then you would use this in a generic conversion method:

 public static <T, U> List<T> xForm(List<U> original, XFormer<T, U> strategy) { List<U> ret = new ArrayList<U>(original.size()); for (U item: original) { ret.add(strategy.xform(item)); } return ret; } 

One of them might look like this:

 List<String> original; List<Long> xFormed = xForm(original, new XFormer<Long, String>() { public Long xForm(String s) { return Long.parseLong(s); } }); 

I use the same strategy in one of my open source projects. Take a look at JodeList on line 166 for an example. In my case, this is a little simplified, because it only converts from Jode to any type, but it needs to be extended to convert between any types.

+2
source

Consider using Apache Commons BeanUitls.populate ().

It will populate each equivalent property from the Bean to another.

0
source

All Articles