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

前端 未结 9 613
借酒劲吻你
借酒劲吻你 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 21:52

    You can write a mapping iterator that decorates an existing iterator and applies a function on it. In this case, the function transforms the objects from one type to another "on-the-fly".

    Something like this:

    import java.util.*;
    
    abstract class Transformer implements Iterable, Iterator {
        public abstract U apply(T object);  
    
        final Iterator source;       
        Transformer(Iterable source)    { this.source = source.iterator(); }
    
        @Override public boolean hasNext() { return source.hasNext(); }
        @Override public U next()          { return apply(source.next()); }
        @Override public void remove()     { source.remove(); } 
    
        public Iterator iterator()      { return this; }
    }
    
    public class TransformingIterator { 
        public static void main(String args[]) {
            List list = Arrays.asList("1", "2", "3");
            Iterable it = new Transformer(list) {
                @Override public Integer apply(String s) {
                    return Integer.parseInt(s);
                }
            };
            for (int i : it) {
                System.out.println(i);
            }
        }
    }
    

提交回复
热议问题