Reputation: 23
I have a class Country
that contains a List<City>
, a class City
contains a List<Street>
, and a class Street
contains a class Human
with a unique ID. I can't understand where is my mistake. I know there are brackets missing somewhere, but I don't know where to put them.
Human finded = country.getCities()
.stream()
.map(cty-> cty.getStreets()
.stream()
.map(strt-> strt.getHumans()
.stream()
.filter(hmn-> hmn.getID().equals(wantedID))
.findFirst()
.orElse(null);
Upvotes: 2
Views: 62
Reputation: 102923
map
turns a single element in a stream into a single other element.
It's useless here - you want to turn, say, a single element (a City
instance) into any number of Street elements. Could be 0 (bit of a weird City), could be 20,000. Mapping a single City to a single Street isn't going to work.
Thus, you want flatMap
instead, which turns a single element in a stream into any number (0, 1, or a million - whatever you like) of elements. Given that one element needs to be turned into X elements, you can't just "return an element" the way map
works. Instead, you return a stream.
county.getCities().stream()
.flatMap(c -> c.getStreets().stream())
.forEach(System.out::println)
;
would print every street in all cities, one per line.
Upvotes: 3