How to get an object from a list that could be a parent or one of the children that matches a given id

huangapple go评论65阅读模式
英文:

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&lt;A&gt; a = mylist.stream()
    .filter(f -&gt; f.getId().equalsIgnoreCase(id) ||
                 f.getChildren().anyMatch(f2 -&gt; 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&lt;A&gt; firstMatch = aList.stream()
        .flatMap(a -&gt; Stream.concat(Stream.of(a), // parent
                a.getChildren().stream().filter(Objects::nonNull))) // its non-null children
        .filter(f -&gt; f.getId().equalsIgnoreCase(id))
        .findFirst(); // finds the corresponding instance of A and not its parent

huangapple
  • 本文由 发表于 2020年10月10日 11:02:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64289554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定