I\'m writing an adapter framework where I need to convert a list of objects from one class to another. I can iterate through the source list to do this as in
Java: Best
As an alternative to the iterator pattern, you can use a abstract generic mapper class, and only override the transform method:
the implementation:
// Generic class to transform collections
public abstract class CollectionTransformer {
abstract F transform(E e);
public List transform(List list) {
List newList = new ArrayList();
for (E e : list) {
newList.add(transform(e));
}
return newList;
}
}
// Method that transform Integer to String
// this override the transform method to specify the transformation
public static List mapIntegerToStringCollection(List list) {
CollectionTransformer transformer = new CollectionTransformer() {
@Override
String transform(Integer e) {
return e.toString();
}
};
return transformer.transform(list);
}
// Example Usage
List integers = Arrays.asList(1,2);
List strings = mapIntegerToStringCollection(integers);
This would be useful is you have to use transformations every time, encapsulating the process. So you can make a library of collection mappers very easy.