Home > Net >  Java Filter list object with Recursive Children
Java Filter list object with Recursive Children

Time:04-08

Given this obj.

public class Menu {

private String id;
private String matchCode;
private List<Menu> children;

//getters and setters

/**
   * Flattened funcition to recursive children list
   */
  public Stream<Menu> flatenned() {
    return Stream.concat(
          Stream.of(this),
          children.stream().flatMap(Menu::flatenned));
  }

}

I need to filter a List and remove all items (parent) that doesn't match to a given matchCode. I also need to filter all the children (at this point there can be 'N' children) by the same field (matchCode)

Since the children is a recursive list structure I found that the method flatenned can help achieve this. (see reference)

So far I have this.

private List<Menu> filterByMatchRoleCode(List<Menu> menuList) {
    return menuList.stream()
      .filter(p -> "string".matches(p.getMatchCode()))
      .map(c -> c.getChildren()
            .stream()
            .map(o -> o.flatenned()
                  .map(Menu::getMatchCode)
                  .filter(v -> "string".matches(v)).collect(Collectors.toList())));
  }

this method filterByMatchRoleCode gives error trying to return the value.

Hope someone can point what I'm missing or can give me a different approach.

CodePudding user response:

I think could be simpler.

    private List<Menu> filterByMatchRoleCode(List<Menu> menuList) {
        return menuList.stream()
                .peek( x -> x.setChildren( filterByMatchRoleCode(x.children)))
                .filter(p -> "string".matches(p.getMatchCode()))
                .collect(Collectors.toList());
    }
  • Related