If I have a List
, how can I turn that into a >
List
that contains all the objects in the same iteration order
Just as @Saravana mentioned:
flatmap is better but there are other ways to achieve the same
listStream.reduce(new ArrayList<>(), (l1, l2) -> {
l1.addAll(l2);
return l1;
});
To sum up, there are several ways to achieve the same as follows:
private List mergeOne(Stream> listStream) {
return listStream.flatMap(List::stream).collect(toList());
}
private List mergeTwo(Stream> listStream) {
List result = new ArrayList<>();
listStream.forEach(result::addAll);
return result;
}
private List mergeThree(Stream> listStream) {
return listStream.reduce(new ArrayList<>(), (l1, l2) -> {
l1.addAll(l2);
return l1;
});
}
private List mergeFour(Stream> listStream) {
return listStream.reduce((l1, l2) -> {
List l = new ArrayList<>(l1);
l.addAll(l2);
return l;
}).orElse(new ArrayList<>());
}
private List mergeFive(Stream> listStream) {
return listStream.collect(ArrayList::new, List::addAll, List::addAll);
}