I have a hierarchical list
like below and I want to convert it to a flat list
.
I have wrote a method called convertToFlatList
Do this by using java-8 flatMap
and recursion
Change
convertToFlatList
method to take only one argument (i,eList
)
If getChildren()
is not null
, then do the recursion or else return the current object
private static List convertToFlatList(List memberList)
{
return memberList.stream().flatMap(i->{
if(Objects.nonNull(i.getChildren())) {
return Stream.concat(Stream.of(i), convertToFlatList(i.getChildren()).stream());
}
return Stream.of(i);
}).collect(Collectors.toList());
}
Output :
[1, 2, 3, 4, 5, 6, 7]