I have an class A
with multiple List
members.
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
}
And a class B
with just 2 attributes:
class B {
String name;
String type;
}
I need to iterate through the various lists in class A
and create class B
object and add to a list like this:
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()));
}
}
}
As the if and for loops are repeated here.
How can I achieve this using Java streams?
Note: There is no relation between the classes X
, Y
and Z
and there is no common interface.
x,z,y
as a type but expecting a list ofB
. – rahul sharma