[FIXED] How to use three streams in java 8 lambdas together?

Issue

I have a class Country that contains a List<City>, a class City contains a List<Street>, and a class Street contains a class Humanwith 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);

Solution

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.

Answered By – rzwitserloot

Answer Checked By – Candace Johnson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published