单链表匹配替换子表java,如何从列表中获取对象,该列表可以是与给定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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值