Como transformar a lista para outra lista

tenho duas listas de objectos; List<X> e List<Y>. X e Y são os ojectos que parecem:

public class X {
    String a;
    String b;
    String v;
    String w;
    String m;
    String n;
}

public class Y {
    String a;
    String b;
    List<A> aList;
}
public class A {
    String v;
    String w;
    List<B> bList;
}
public class B {
    String m;
    String n;
}

Como transformar List<X> em List<Y> baseado numa regra:
Os valores de alguns campos devem ser iguais.
Por exemplo:
Em List<Y>, para um objecto Y, o valor do campo a deve ser igual.
No campo de Y List<A>, para um objecto a, o valor do Campo w deve ser igual.
No campo a List<B>, para um objecto B, O valor do campo m deve ser igual e assim por diante.

goiaba tem este método, listas # transformar , Mas eu não sei como transformar.

Ou de outra forma?

Author: Andrejs, 2011-09-12

6 answers

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

É melhor ler os documentos da API para as listas .transformar () e Função , mas basicamente o chamador da transformada fornece um objeto Function que converte um F para um T.

Por exemplo, se você tem um List<Integer> intList e você deseja criar um List<String>, tal que cada elemento de a última contém o inglês representação de que o número (1 torna-se "um", etc) e você tem acesso a uma classe, tais como IntToEnglish então

Function<Integer, String> intToEnglish = 
    new Function<Integer,String>() { 
        public String apply(Integer i) { return new IntToEnglish().english_number(i); }
    };

List<String> wordsList = Lists.transform(intList, intToEnglish);
Faz essa conversão.

Você pode aplicar o mesmo padrão para transformar o seu List<X> para List<Y>

 71
Author: Miserable Variable, 2016-08-11 17:50:13

Com Java lambda:

public static <K,V,Q extends K> List<V> transform( final List<Q> input, final java.util.function.Function<K,V> tfunc ) {
    if( null == input ) {
        return null;
    }
    return input.stream().map(tfunc).collect( Collectors.toList() );
}

Só precisas de implementar: hipoteca.util.funcao.Função

 7
Author: biliboc, 2015-10-26 16:53:37
Que tal isto?
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.collect.Lists;

public class GuavaTransform {
    public static void main(String[] args) {
        List<X> xList = new ArrayList<X>();
        xList.add(new X("a", "b", "v", "w", "m", "n"));
        xList.add(new X("a1", "b1", "v1", "w1", "m1", "n1"));
        for(X elem: xList) {
            System.out.println("An instance of X:"+ elem);
        }
        System.out.println();
        List<Y> yList = Lists.transform(xList, new TransformXY());
        for(Y elem: yList) {
            System.out.println("The corresponding instance of Y: \n"+elem);
        }
    }
}

class TransformXY implements Function<X, Y> {

    @Override
    public Y apply(X x) {
        List<B> bList = new ArrayList<B>();
        bList.add(new B(x.m, x.n));
        List<A> aList = new ArrayList<A>();
        aList.add(new A(x.v, x.w, bList));
        return new Y(x.a, x.b, aList);
    }
}

class X {
    String a;
    String b;
    String v;
    String w;
    String m;
    String n;
    X(String a, String b, String v, String w, String m, String n) {
        super();
        this.a = a;
        this.b = b;
        this.v = v;
        this.w = w;
        this.m = m;
        this.n = n;
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        sb.append(a+",");
        sb.append(b+",");
        sb.append(v+",");
        sb.append(w+",");
        sb.append(m+",");
        sb.append(n);
        sb.append(")");
        return sb.toString();
    }
}
class Y {
    String a;
    String b;
    List<A> aList;
    Y(String a, String b, List<A> aList) {
        super();
        this.a = a;
        this.b = b;
        this.aList = aList;
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(a+"\n");
        sb.append(b+"\n");
        for(A elem: aList) {
            sb.append(elem+"\n");
        }
        return sb.toString();
    } 
}
class A {
    String v;
    String w;
    List<B> bList;
    A(String v, String w, List<B> bList) {
        super();
        this.v = v;
        this.w = w;
        this.bList = bList;
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("--------"+v+"\n");
        sb.append("--------"+w+"\n");
        for(B elem: bList) {
            sb.append(elem+"\n");
        }
        return sb.toString();
    }

}
class B {
    String m;
    String n;
    B(String m, String n) {
        super();
        this.m = m;
        this.n = n;
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("----------------"+m+"\n");
        sb.append("----------------"+n+"\n");
        return sb.toString();
    }
}

Saída da consola:

An instance of X:(a,b,v,w,m,n)
An instance of X:(a1,b1,v1,w1,m1,n1)

The corresponding instance of Y: 
a
b
--------v
--------w
----------------m
----------------n



The corresponding instance of Y: 
a1
b1
--------v1
--------w1
----------------m1
----------------n1
 6
Author: blackcompe, 2011-09-12 06:18:43

Java 8 style, IntelliJ IDEA helped me out:

List<X> xList = new ArrayList<>();
List<Y> yList = xList
        .stream()
        .map(X::getY)
        .collect(Collectors.toList());
 1
Author: Isaace, 2018-01-14 17:05:21

Assumir que tem dois objectos pode interconversion, Coach e EntityBase

1.declarar o método genérico

   public static <TSourse, TResult> void ToList(List<TSourse> list, List<TResult> results) {
    if (list.size() > 0) {
        for (TSourse obj : list) {
            TResult tResult = (TResult) obj;
            if (tResult == null) {
                throw new AppException("error....");
            }
            results.add(tResult);
        }
    }
}

2.chame este método

  List<EntityBase> entityBaseList = new ArrayList<>();
    Coach coach = new Coach();
    coach.setId("123");
    entityBaseList.add(coach);

    List<Coach> coachList = new ArrayList<>();
    ToList(entityBaseList, coachList);
    //will complete List<AObj> to another List<BObj>
 0
Author: anuo, 2017-08-29 03:11:16

O mesmo que @Isaace, mas com a sintaxe lambda (consegui-a de Este exemplo):

List<X> xList = new ArrayList<>();
List<Y> yList = xList
        .stream()
        .map(n -> someTransformFunc(n))
        .collect(Collectors.toList());
 0
Author: bartaelterman, 2018-07-05 08:00:15