I have Item
and Address
classes:
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"
.
I try below but in Eclipse it shows:
"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 can use anyMatch
on the inner stream:
items.stream().filter(a->a.getAddress().stream().
anyMatch(b->"lane1".equals(b.getLane()))).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.
So as answered by @Sweeper, you can use 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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.