如何转换List< X>到另一个列表< Y> [英] How to transform List<X> to another List<Y>
问题描述
我有两个对象列表; 列表< X>
和列表< Y>
。 X
和 Y
是看起来像的对象:
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;
}
如何转换列表< X>
进入列表< Y>
基于规则:
某些字段的值必须相等。
例如:
在列表< Y>
中,对于一个对象Y,字段a的值必须相等。
在Y的字段中列表< A>
,对于一个对象A,字段w的值必须相等。
在A的字段中列表< B>
,对于一个对象B,字段m的值必须相等,等等。
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有这种方法,列出#transform ,但我不知道如何转换。
Guava has this method, Lists#transform, but I don't know how to transform.
还是其他任何方式?
推荐答案
public static <F,T> List<T> transform(List<F> fromList,
Function<? super F,? extends T> function
您可能想要阅读 Lists.transform()和功能,但基本上转换的调用者提供了函数
将 F
转换为 T
的对象。
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
.
例如,如果你有一个 List< Integer> intList
,你想创建一个 List< String>
这样后者的每个元素都包含该数字的英语表示(1变为1等),并且您可以访问类,例如 IntToEnglish 然后
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);
进行转换。
您可以应用相同的模式将列表< X>
转换为列表< Y>
You can apply the same pattern to transform your List<X>
to List<Y>
这篇关于如何转换List< X>到另一个列表< Y>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!