How to transform List<X> to another List<Y>

zhm picture zhm · Sep 12, 2011 · Viewed 83.3k times · Source

I have two lists of objects; List<X> and List<Y>. X and Y are ojects that look like:

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

How transform List<X> into List<Y> based on a rule:
Some fields' values must be equal.
For example:
In List<Y>, for one object Y, field a's value must equal.
In Y's field List<A>, for one object A, field w's value must equal.
In A's field List<B>, for one object B, field m's value must equal and so on.


Guava has this method, Lists#transform, but I don't know how to transform.

Or any other way?

Answer

Miserable Variable picture Miserable Variable · Sep 12, 2011
public static <F,T> List<T> transform(List<F> fromList,
                                      Function<? super F,? extends T> function

You might want to read up the API docs for Lists.transform() and Function, but basically the caller of the transform provides a Function object that converts an F to a T.

For example if you have a List<Integer> intList and you want to create a List<String> such that each element of the latter contains the english representation of that number (1 becomes "one" etc) and you have a access to a class such as IntToEnglish then

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);

Does that conversion.

You can apply the same pattern to transform your List<X> to List<Y>