带有递归子级的Java Filter列表对象



给定此目标

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));
}
}

我需要过滤一个列表并删除所有与给定matchCode不匹配的项(父项(。我还需要通过相同的字段(matchCode(过滤所有子项(此时可能有'N'个子项(

由于children是一个递归列表结构,我发现flatenned方法可以帮助实现这一点。(参见参考资料(

到目前为止,我有这个。

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())));
}

此方法filterByMatchRoleCode在尝试返回值时出错。

希望有人能指出我缺少的东西,或者给我一个不同的方法。

我认为可以更简单。

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());
}

最新更新