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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With