问题
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