I have an object as follows and a list as per the object Type:
public class A{
private String x;
private String y;
private List<A> child = new ArrayList<>();
}
What I want to do is flatten the list and make a list of Object A together with its children;
Currently I am doing in three separate statements as per below:
List<A> ChildElements = map.values()
.stream()
.flatMap(entry -> entry.getChild().stream())
.collect(Collectors.toList());
List<A> RootElements = map.values()
.stream()
.collect(Collectors.toList());
List<A> elements = Stream.concat(ChildElements.stream(),RootElements.stream()).collect(Collectors.toList());
I wanted to know if the above can be refactored in one statement.
Thank you.
map.values().stream().flatMap(entry -> { final ArraryList<A> result = new ArrayList>(entry.getChild().stream())); result.add(entry); return result.stream(); }).collect(Collectors.toList());