How to convert multiple list into single list using Java streams?
Since you don't have a common interface, you would have to use a forEach
method to iterate through each list.
a.getXList().forEach(i -> b.add(new B(i.getDesc(), i.getXType())));
a.getYList().forEach(i -> b.add(new B(i.getName(), i.getYType())));
a.getZList().forEach(i -> b.add(new B(i.getDescription(), i.getZType())));
You can use Stream.concat()
like following
public List<B> convertList (A a) {
return Stream.concat(Stream.concat(a.getXList().stream().map(x -> new B(x.getDesc(), x.getXType()))
, a.getYList().stream().map(y -> new B(y.getName(), y.getYType())))
, a.getZList().stream().map(z -> new B(z.getDescription(), z.getZType()))).collect(Collectors.toList());
}
You are using the different property for X, Y, Z class, and not having common interface, you can add one by one in the list.
b.addAll(a.getXList().stream().map(x ->new B(x.getDesc(), x.getXType())).collect(Collectors.toList()));
b.addAll(a.getYList().stream().map(y ->new B(y.getName(), y.getYType())).collect(Collectors.toList()));
b.addAll(a.getZList().stream().map(z ->new B(z.getDescription(), z.getZType())).collect(Collectors.toList()));
Since your X
, Y
and Z
types don't have a common super-type, you have to convert them into some common type, such as Map.Entry<String,String>
.
You can create a Stream
of all pairs of names and types, and then map it to instances of B
:
List<B> b =
Stream.of(
a.getXList().stream().map(x -> new SimpleEntry<>(x.getDesc(),x.getXType())),
a.getYList().stream().map(y -> new SimpleEntry<>(y.getName(),y.getYType())),
a.getZList().stream().map(z -> new SimpleEntry<>(z.getDescription(),z.getZType())))
.flatMap(Function.identity())
.map(e -> new B(e.getKey(), e.getValue()))
.collect(Collectors.toList());
Or directly generate B
instances:
List<B> b =
Stream.of(
a.getXList().stream().map(x -> new B(x.getDesc(),x.getXType())),
a.getYList().stream().map(y -> new B(y.getName(),y.getYType())),
a.getZList().stream().map(z -> new B(z.getDescription(),z.getZType())))
.flatMap(Function.identity())
.collect(Collectors.toList());