Arthur
Arthur

Reputation: 3473

How to filter inner Set in Java 8 stream?

I have List with objects

 List<FrameworkAdminLeftMenu> menu = getMenuFromDB();

each FrameworkAdminLeftMenu object has method

public Set<FrameworkAdminLeftMenuCategories> getFrameworkAdminLeftMenuCategorieses() {
        return this.frameworkAdminLeftMenuCategorieses;
}

and method

public String getCssClassName() {
        return this.cssClassName;
}

each FrameworkAdminLeftMenuCategories object has method

public Integer getId() {
        return this.id;
}

How can I filter all List and Set to get FrameworkAdminLeftMenuCategories object by getId(1) ?

For example, something like

 List<FrameworkAdminLeftMenu> collect = menu.stream()
                .filter(
                        f -> f
                        .getCssClassName()
                        .contains("adm-content")
                )
                .collect(Collectors.toList());

         List<FrameworkAdminLeftMenuCategories> categs = collect
                .stream()
                .filter(
                        f -> f.
                        getFrameworkAdminLeftMenuCategorieses()
                        .stream()
                        .filter(c -> c.getId() == 1)
                )
                .collect(Collectors.toList());

Upvotes: 2

Views: 1797

Answers (1)

tobias_k
tobias_k

Reputation: 82929

If I understand the question correctly, you want to aggregate the categories from all the sets and filter the ones with the right ID. In this case, you should use flatMap.

Try something like this (untested, obviously):

 List<FrameworkAdminLeftMenuCategories> categs = menu.stream()
        .filter(f -> f.getCssClassName().contains("adm-content"))
        .flatMap(f -> f.getFrameworkAdminLeftMenuCategorieses().stream())
        .filter(c -> c.getId() == 1)
        .collect(Collectors.toList());

Upvotes: 1

Related Questions