Java: Converting lists of one element type to a list of another type

前端 未结 9 614
借酒劲吻你
借酒劲吻你 2021-02-01 21:18

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

9条回答
  •  生来不讨喜
    2021-02-01 22:01

    As an alternative to the iterator pattern, you can use a abstract generic mapper class, and only override the transform method:

    1. create a generic collection mapper for any data type
    2. [optional] create a library of methods that transform between different data types (and override the method)
    3. use that library

    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.

提交回复
热议问题