Iterating through nested collections to find first sub-sub-sub element matching a criterion

狂风中的少年 提交于 2019-12-11 08:07:23

问题


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.


回答1:


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:

  • Why filter() after flatMap() is "not completely" lazy in Java streams?
  • In Java, how do I efficiently and elegantly stream a tree node's descendants?


来源:https://stackoverflow.com/questions/39828710/iterating-through-nested-collections-to-find-first-sub-sub-sub-element-matching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!