I have a class A with an id of type String and a list of children which is of the same type as parent (Class A) but Children could be null or the children list could be empty. Given an id, need to find the object from a list that could match with the parent object id or the Child object id using java 8 streams.
I have the below code, that is returning the parent object even though the id matches the child object. I needed the child object.
Optional a = mylist.stream()
.filter(f -> f.getId().equalsIgnoreCase(id) ||
f.getChildren().anyMatch(f2 -> f2.getId().equalsIgnoreCase(id)))
.findFirst();
解决方案
what you are ending up performing within the filter, would return the parent either when the parent matches the criteria or even if one of its children matches the criteria because of the || condition accompanied with anyMatch amongst children.
if you were to return the corresponding A instance only, you would have to flatMap all the A objects and then perform the filter to find the first match.
Optional firstMatch = aList.stream()
.flatMap(a -> Stream.concat(Stream.of(a), // parent
a.getChildren().stream().filter(Objects::nonNull))) // its non-null children
.filter(f -> f.getId().equalsIgnoreCase(id))
.findFirst(); // finds the corresponding instance of A and not its parent