How to transform List<X> to another List<Y> [duplicate]

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?


Solution 1:

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>

Solution 2:

With 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() );
}

You just need to implement: java.util.function.Function