代码之家  ›  专栏  ›  技术社区  ›  Mike Chaliy

在Java中,将一个列表映射到另一个列表最优雅的方式是什么?

  •  3
  • Mike Chaliy  · 技术社区  · 15 年前

    我是Java新手,请耐心等待。

    将列表映射(转换)为列表是很常见的。有些语言有不同的语言 map 方法,一些(C#) Select for 循环是唯一的选择吗?

    我希望能够做到以下几点:

    List<Customer> customers = new ArrayList<Customer>();
    ...
    List<CustomerDto> dtos = customers.convert(new Converter(){
      public convert(c) {
        return new CustomerDto();
      }
    })
    

    我错过了什么?请给我一个起点。

    6 回复  |  直到 15 年前
        1
  •  5
  •   Steve McLeod    15 年前

    在Java中没有内置的方法来实现这一点——您必须编写或使用帮助器类。 Google Collections 包括

    public static <F,T> List<T> transform(List<F> fromList,
                                      Function<? super F,? extends T> function)
    

    请注意,这会根据需要延迟转换源列表中的项。

        2
  •  4
  •   bruno conde    15 年前

    我在飞行中实现了一些东西。看看这是否对你有帮助。如果没有,请按照建议使用谷歌收藏。

    public interface Func<E, T> {
        T apply(E e);
    }
    
    public class CollectionUtils {
    
        public static <T, E> List<T> transform(List<E> list, Func<E, T> f) {
            if (null == list)
                throw new IllegalArgumentException("null list");
            if (null == f)
                throw new IllegalArgumentException("null f");
    
            List<T> transformed = new ArrayList<T>();
            for (E e : list) {
                transformed.add(f.apply(e));
            }
            return transformed;
        }
    }
    
    List<CustomerDto> transformed = CollectionUtils.transform(l, new Func<Customer, CustomerDto>() {
        @Override
        public CustomerDto apply(Customer e) {
            // return whatever !!!
        }
    });
    
        3
  •  2
  •   Mike Pone    15 年前

    只要customerDto扩展了Customer,这就行了

       List<Customer> customers = new ArrayList<Customer>();
    
       List<CustomerDto> dtos = new ArrayList<CustomerDto>(customers);
    

    List<Customer> customers = new ArrayList<Customer>();
    
    List<CustomerDto> dtos = new ArrayList<CustomerDto>();
    
    for (Customer cust:customers) {
      dtos.add(new CustomerDto(cust));
    }
    
        4
  •  0
  •   erickson    15 年前

    目前还没有一种方法可以将这样的映射函数应用于Java List (或其他收藏)。将提供此功能的闭包在即将发布的JDK 7版本中得到了认真考虑,但由于缺乏共识,它们被推迟到了稍后的版本。

    使用当前构造,可以实现如下内容:

    public abstract class Convertor<P, Q>
    {
    
      protected abstract Q convert(P p);
    
      public static <P, Q> List<Q> convert(List<P> input, Convertor<P, Q> convertor)
      {
        ArrayList<Q> output = new ArrayList<Q>(input.size());
        for (P p : input)
          output.add(convertor.convert(p));
        return output;
      }
    
    }
    
        5
  •  0
  •   Peter Lawrey    15 年前

    就我个人而言,我发现以下内容更短、更简单,但如果你觉得函数式方法更简单,你可以这样做。如果其他Java开发人员可能需要阅读/维护代码,我建议他们使用这种方法,他们可能会觉得更舒服。

    List<CustomerDto> dtos = new ArrayList<CustoemrDto>();
    for(Customer customer: customers)
       dtos.add(new CustomerDto());
    

    你可能会发现这个图书馆很有趣 Functional Java