What is the most elegant way to map one list to another in Java?

I am new to Java, so please be patient.

Usually to convert (convert) lists to lists. Some languages ​​have a method map, some (C #) Select. How is this done with Java? Is a loop the foronly option?

I expect I can do something like this:

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

Did I miss something? Please give me a starting point.

+3
source share
6 answers

I implemented something on the fly. See if this helps you. If not, use Google Collections as suggested.

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 !!!
    }
});
+4
source

Java - . Google

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

, , . Google, Java.

, .

+5

Dto ,

   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));
}
+2

​​ 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;
  }

}
0

, , , . Java, , / , , .

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

Java

0

Source: https://habr.com/ru/post/1708361/


All Articles