【发布时间】:2020-05-25 10:07:59
【问题描述】:
我有一个班级 A 有多个 List 成员。
class A {
List<X> xList;
List<Y> yList;
List<Z> zList;
// getters and setters
}
class X {
String desc;
String xtype;
// getters and setters
}
class Y {
String name;
String ytype;
//getters and setters
}
class Z {
String description;
String ztype;
// getters and setters
}
还有一个只有 2 个属性的类 B:
class B {
String name;
String type;
}
我需要遍历A 类中的各种列表并创建B 类对象并添加到这样的列表中:
public void convertList(A a) {
List<B> b = new ArrayList<>();
if (!a.getXList().isEmpty()) {
for (final X x : a.getXList()) {
b.add(new B(x.getDesc(), x.getXType()));
}
}
if (!a.getYList().isEmpty()) {
for (final Y y : a.getYList()) {
b.add(new B(y.getName(), y.getYType()));
}
}
if (!a.getZList().isEmpty()) {
for (final Z z : a.getZList()) {
b.add(new B(z.getDescription(), z.getZType()));
}
}
}
因为 if 和 for 循环在这里重复。
如何使用 Java 流实现这一点?
注意:X、Y 和 Z 类之间没有关系,也没有通用接口。
【问题讨论】:
-
您是否尝试过使用 FlatMap,如果没有请看这里。 stackoverflow.com/questions/23112874/…
-
X、Y 和 Z 是扩展同一个基类还是实现包含 getName 和 getType 的同一个接口?
-
正确解决问题,因为您有多个列表,但将
x,z,y作为类型传递,但需要B的列表。 -
@JoakimDanielson 更新了问题。没有基类或接口。这些类中的属性都是不同的。我需要根据每个类的 getter 转换为 B 类。
标签: java java-stream