这个怎么样?
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
public class GuavaTransform {
public static void main(String[] args) {
List<X> xList = new ArrayList<X>();
xList.add(new X("a", "b", "v", "w", "m", "n"));
xList.add(new X("a1", "b1", "v1", "w1", "m1", "n1"));
for(X elem: xList) {
System.out.println("An instance of X:"+ elem);
}
System.out.println();
List<Y> yList = Lists.transform(xList, new TransformXY());
for(Y elem: yList) {
System.out.println("The corresponding instance of Y: \n"+elem);
}
}
}
class TransformXY implements Function<X, Y> {
@Override
public Y apply(X x) {
List<B> bList = new ArrayList<B>();
bList.add(new B(x.m, x.n));
List<A> aList = new ArrayList<A>();
aList.add(new A(x.v, x.w, bList));
return new Y(x.a, x.b, aList);
}
}
class X {
String a;
String b;
String v;
String w;
String m;
String n;
X(String a, String b, String v, String w, String m, String n) {
super();
this.a = a;
this.b = b;
this.v = v;
this.w = w;
this.m = m;
this.n = n;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append(a+",");
sb.append(b+",");
sb.append(v+",");
sb.append(w+",");
sb.append(m+",");
sb.append(n);
sb.append(")");
return sb.toString();
}
}
class Y {
String a;
String b;
List<A> aList;
Y(String a, String b, List<A> aList) {
super();
this.a = a;
this.b = b;
this.aList = aList;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(a+"\n");
sb.append(b+"\n");
for(A elem: aList) {
sb.append(elem+"\n");
}
return sb.toString();
}
}
class A {
String v;
String w;
List<B> bList;
A(String v, String w, List<B> bList) {
super();
this.v = v;
this.w = w;
this.bList = bList;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("--------"+v+"\n");
sb.append("--------"+w+"\n");
for(B elem: bList) {
sb.append(elem+"\n");
}
return sb.toString();
}
}
class B {
String m;
String n;
B(String m, String n) {
super();
this.m = m;
this.n = n;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("----------------"+m+"\n");
sb.append("----------------"+n+"\n");
return sb.toString();
}
}
控制台输出:
An instance of X:(a,b,v,w,m,n)
An instance of X:(a1,b1,v1,w1,m1,n1)
The corresponding instance of Y:
a
b
The corresponding instance of Y:
a1
b1
Y
中有一个List<A>
,这个列表应该有多少个A
对象?如果超过一个,它们是否都具有相同的值? - NullUserException