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

前端 未结 9 616
借酒劲吻你
借酒劲吻你 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:53

    Well, you could create your own iterator wrapper class to do this. But I doubt that you would save much by doing this.

    Here's a simple example that wraps any iterator to a String iterator, using Object.toString() to do the mapping.

    public MyIterator implements Iterator {
    
        private Iterator it;
    
        public MyIterator(Iterator it) {
            this.it = it;
        }
    
        public boolean hasNext() {
            return it.hasNext();
        }
    
        public String next() {
            return it.next().toString();
        }
    
        public void remove() {
            it.remove();
        }
    }
    

提交回复
热议问题