I have a hierarchical list
like below and I want to convert it to a flat list
.
I have wrote a method called convertToFlatList
If you use Java 8, just add this method to the Member
class:
public Stream streamAll(){
if(getChildren() == null){
return Stream.of(this);
}
return Stream.concat(Stream.of(this), getChildren().stream().flatMap(Member::streamAll));
}
Alternatively, you can remove the null check if you always initialize children
to an empty list :
public Stream streamAll(){
return Stream.concat(Stream.of(this), getChildren().stream().flatMap(Member::streamAll));
}
Then to get the flat list:
List convertedList = memberList.stream()
.flatMap(Member::streamAll)
.collect(Collectors.toList());