[英]Use Java filter on stream with in a stream filter
I have Item
and Address
classes: 我有
Item
和Address
类:
public class Item {
String name;
List<Address> address;
}
public class Address {
String name;
String lane;
}
Suppose I have a item list and want to filter items that has lane as "lane1"
. 假设我有一个项目列表,并希望过滤具有
"lane1"
项目的项目。
I try below but in Eclipse it shows: 我尝试下面但在Eclipse中它显示:
"Type mismatch: cannot convert from Stream Address to boolean"
“类型不匹配:无法从流地址转换为布尔值”
items.stream().filter(a->a.getAddress().stream().
filter(b->b.getLane().equals("lane1"))).collect(Collectors.toList());
You are getting type mismatch error because filter has to return boolean result and in your case inner stream is returning Stream<Address>
not boolean. 您遇到类型不匹配错误,因为过滤器必须返回布尔结果,在您的情况下,内部流返回
Stream<Address>
而不是布尔值。
So as answered by @Sweeper, you can use anyMatch
, 所以@Sweeper回答说,你可以使用
anyMatch
,
// you can directly use predicate in anyMatch
Predicate<? super Address> equalsLane1 = address->address.getLane().equals("lane1");
List<Item> lane1 = items.stream().filter(ele ->
ele.getAddress().stream().anyMatch(equalsLane1)).collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.