-1

My object is a collection of profiles that inside has a set of PerfilMenunode

public class Perfil {
    [...]
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "ID_PERFIL")
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<PerfilMenunode> perfilMenunodes;

What I want to do is this function but only using stream

public PerfilMenunode darPerfilMenuNode(List<Perfil> perfiles) {
    PerfilMenunode perfilMenunode = null;
    for (Perfil perfil : perfiles) {
        perfilMenunode = perfil.getPerfilMenunodes().stream().filter(pm -> pm.getMenunode().getNombreCorto().equals(Constante.MENU_ADMINPERFIL_NOMBRECORTO)).findFirst().orElse(null);
        if(perfilMenunode!=null) {
            return perfilMenunode;
        }
    }
    return perfilMenunode;
}

Any solution?

Luis Lopez
  • 11
  • 1
  • @Naman OP doesnt want a list, reopened – Yassin Hajaj Apr 23 '21 at 06:37
  • Not sure why the history/audit is no more visible here. But would [this thread](https://stackoverflow.com/questions/54528857/how-to-filter-liststring-object-collection-with-java-stream) help? – Naman Apr 23 '21 at 07:29

2 Answers2

1

It would give the following using flatMap

public PerfilMenunode darPerfilMenuNode(List<Perfil> perfiles) {
    return perfiles.stream()
            .map(Perfil::getPerfilMenunodes)
            .flatMap(Collection::stream)
            .filter(pm -> pm.getMenunode()
                            .getNombreCorto()
                            .equals(Constante.MENU_ADMINPERFIL_NOMBRECORTO)
            )
            .findFirst()
            .orElse(null);
}

But if you're using , you can use Stream#mapMulti instead of flatMap, it gives better performance, even more if your perfilMenunodes are small collections or empty collections

public PerfilMenunode darPerfilMenuNode(List<Perfil> perfiles) {
    return perfiles.stream()
            .mapMulti((Perfil perfil, Consumer<PerfilMenunode> consumer) -> {
                perfil.getPerfilMenunodes().forEach(consumer::accept);
            })
            .filter(pm -> pm.getMenunode()
                            .getNombreCorto()
                            .equals(Constante.MENU_ADMINPERFIL_NOMBRECORTO)
            )
            .findFirst()
            .orElse(null);
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
0

I think it can look like this:

public PerfilMenunode darPerfilMenuNode(List<Perfil> perfiles) {
   return perfiles.stream().flatMap(p -> p.getPerfilMenunodes().stream())
        .filter(pm -> pm.getMenunode().getNombreCorto().equals(Constante.MENU_ADMINPERFIL_NOMBRECORTO))
        .findFirst().orElse(null);
}
Sergey Vasnev
  • 783
  • 5
  • 18