2

I have an object with a List of other objects, each other object has a List etc. I need to find in the hierarchy the first (and unique) last element in the hierarchy that has a property matching some value. Seeing my present code will be clearer :

    @Override
public Poste findByNumeroAndMillesime(String numero, Millesime millesime) {
    return millesime
            .getDivisions()
            .stream()
            .filter(
                    division -> division
                    .getGroupes()
                    .stream()
                    .filter(
                          groupe -> groupe
                          .getClasses()
                          .stream()
                          .filter(
                                  classe -> classe
                                  .getSousClasses()
                                  .stream()
                                  .filter(
                                          sousClasse -> sousClasse
                                          .getPostes()
                                          .stream()
                                          .filter(poste -> numero.equals(poste.getNumero()))
                                          .findFirst()
                                          .get()
                                          ))));

}

I need to return the Poste having the same numero as that passed as a parameter.

Thanks in advance.

Sartorius
  • 499
  • 5
  • 12
Dapangma
  • 127
  • 1
  • 1
  • 10

1 Answers1

5

You could try flatMap like this:

Optional<Postes> first = 
        millesime.getDivisions()
              .stream()
              .flatMap(m -> m.getGroupes().stream())
              .flatMap(m -> m.getClasses().stream())
              .flatMap(m -> m.getSousClasses().stream())
              .flatMap(m -> m.getPostes().stream())
              .filter(postes -> numero.equals(postes.getNumero()))
              .findFirst();

But be aware of issues you may encounter if you have huge tree, as flatMap is not completly lazy. See:

Community
  • 1
  • 1
user140547
  • 7,750
  • 3
  • 28
  • 80
  • Thanks a lot for this answer, now it compiles, and specially for the links you provided. I have a basis now to understand what's going on. I'll look into it straight away. I do have lazy initializatio issues... – Dapangma Oct 04 '16 at 09:32
  • Thank you! Your answer was what I was exactly looking for - I wouldn't have posted [this](http://stackoverflow.com/questions/40619075/how-to-return-object-instead-of-stream-using-peek-or-anymatch?noredirect=1#comment68472649_40619075) otherwise. – mohsenmadi Nov 15 '16 at 21:17