Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Java filter on stream with in a stream filter

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());
like image 827
Harshana Avatar asked Apr 27 '26 01:04

Harshana


2 Answers

You can use anyMatch on the inner stream:

items.stream().filter(a->a.getAddress().stream().
      anyMatch(b->"lane1".equals(b.getLane()))).collect(Collectors.toList());
like image 76
Sweeper Avatar answered Apr 28 '26 17:04

Sweeper


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());
like image 35
Vikas Yadav Avatar answered Apr 28 '26 17:04

Vikas Yadav