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

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

    Here's an on-the-fly approach. (There must be something already like this in the jdk; I just can't find it.)

      package com.gnahraf.util;
    
      import java.util.AbstractList;
      import java.util.List;
      import java.util.Objects;
      import java.util.function.Function;
    
      /**
       * 
       */
      public class Lists {
    
        private Lists() { }
    
    
        public static  List transform(List source, Function mapper) {
          return new ListView(source, mapper);
        }
    
        protected static class ListView extends AbstractList {
    
          private final List source;
          private final Function mapper;
    
          protected ListView(List source, Function mapper) {
            this.source = Objects.requireNonNull(source, "source");
            this.mapper = Objects.requireNonNull(mapper, "mapper");
          }
    
          @Override
          public V get(int index) {
            return mapper.apply(source.get(index));
          }
    
          @Override
          public int size() {
            return source.size();
          }
    
        }
    
      }
    

提交回复
热议问题