How to transform List to another List [duplicate]

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>

Leave a Comment