英文:
How to get an object from a list that could be a parent or one of the children that matches a given id
问题
我有一个名为 class A
的类,具有一个类型为String的id,以及一个子类列表,子类与父类(Class A)的类型相同,但子类可以为null或子类列表可以为空。给定一个id,需要从列表中找到与父对象id或子对象id匹配的对象,使用java 8流进行操作。
以下是代码部分:
Optional<A> a = mylist.stream()
.filter(f -> f.getId().equalsIgnoreCase(id) ||
f.getChildren().stream().anyMatch(f2 -> f2.getId().equalsIgnoreCase(id)))
.findFirst();
英文:
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> a = mylist.stream()
.filter(f -> f.getId().equalsIgnoreCase(id) ||
f.getChildren().anyMatch(f2 -> f2.getId().equalsIgnoreCase(id)))
.findFirst();
答案1
得分: 1
在filter
内部执行的操作会在满足父项条件或者其任意子项条件满足时返回父项,这是因为在子项中使用了||
条件和anyMatch
函数。
如果你只想返回相应的A
实例,你需要使用flatMap
对所有的A
对象执行操作,然后再进行过滤以找到第一个满足条件的实例。
Optional<A> firstMatch = aList.stream()
.flatMap(a -> Stream.concat(Stream.of(a), // 父项
a.getChildren().stream().filter(Objects::nonNull))) // 非空子项
.filter(f -> f.getId().equalsIgnoreCase(id))
.findFirst(); // 找到对应的 A 实例而不是其父项
英文:
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<A> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论