如何从列表中获取对象,该列表可以是与给定ID匹配的父级或子级之一 [英] How to get an object from a list that could be a parent or one of the children that matches a given id

查看:74
本文介绍了如何从列表中获取对象,该列表可以是与给定ID匹配的父级或子级之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个class A,其ID类型为String,并且具有与父代(A类)具有相同类型的子代列表,但是Children可以为null或子代列表可以为空.给定一个ID,需要使用Java 8流从一个列表中找到与父对象ID或子对象ID匹配的对象.

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.

我有以下代码,即使id与子对象匹配,该代码仍将返回父对象.我需要子对象.

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();

推荐答案

您最终在filter中执行的操作将在父项符合条件时或即使其子项之一符合条件时返回父项.因为||病情伴有anyMatch在儿童中.

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.

如果仅返回相应的A实例,则必须flatMap所有A对象,然后执行过滤器以查找第一个匹配项.

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

这篇关于如何从列表中获取对象,该列表可以是与给定ID匹配的父级或子级之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆