+-

参见英文答案 > How can I call a method on each element of a List? 5个
我有两个对象列表;列表与LT; X>和列表< Y>. X和Y是看起来像的对象:
我有两个对象列表;列表与LT; X>和列表< Y>. X和Y是看起来像的对象:
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;
}
如何变换List< X>到列表< Y>基于规则:
某些字段的值必须相等.
例如:
在List< Y>中,对于一个对象Y,字段a的值必须相等.
在Y的字段列表< A>中,对于一个对象A,字段w的值必须相等.
在A的字段列表< B>中,对于一个对象B,字段m的值必须相等,依此类推.
番石榴有这种方法,Lists#transform,但我不知道如何改造.
还是其他任何方式?
最佳答案
public static <F,T> List<T> transform(List<F> fromList,
Function<? super F,? extends T> function
您可能想要读取Lists.transform()和Function的API文档,但基本上转换的调用者提供了一个将F转换为T的Function对象.
例如,如果您有一个List< Integer> intList,你想创建一个List< String>这样后者的每个元素都包含该数字的英语表示(1变为“一”等),并且您可以访问诸如IntToEnglish之类的类
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);
那转换.
您可以应用相同的模式来转换List< X>列出< Y>
点击查看更多相关文章
转载注明原文:java – 如何将List转换为另一个列表 - 乐贴网