6

I am writing a method which will return a list of regiondata, i am doing in following manner but getting error

@Override
    public List<RegionData> getAllRegionsForDeliveryCountries()
    {
        final List<RegionData> regionData = new ArrayList<>();
        final List<String> countriesIso = getCountryService().getDeliveryCountriesIso();
        regionData = countriesIso.stream().map(c->i18nFacade.getRegionsForCountryIso(c)).collect(Collectors.toList());
        return regionData;
    }

I am getting error on

type mismatch: cannot convert from List<List<RegionData>> to List<RegionData>

on line regionData = countriesIso.stream().map(c->i18nFacade.getRegionsForCountryIso(c)).collect(Collectors.toList());

The function i18nFacade.getRegionsForCountryIso(c) is returning a list of region data, I want to combine these lists into single list. I tried with lambda but unable to do so.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Devendra
  • 1,864
  • 6
  • 29
  • 49

3 Answers3

10

You need to use flatMap with stream.

regionData = countriesIso.stream()
    .flatMap(c -> i18nFacade.getRegionsForCountryIso(c).stream())
    .collect(Collectors.toList());
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Raghav
  • 4,590
  • 1
  • 22
  • 32
  • Or `regionData = countriesIso.stream().map(i18nFacade::getRegionsForCountryIso).flatMap(List::stream).toList()`. – MC Emperor Jun 02 '23 at 17:26
5

Use flatMap:

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

regionData = countriesIso
               .stream()
               .flatMap(c -> i18nFacade.getRegionsForCountryIso(c)
               .stream())
               .collect(Collectors.toList());
thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23
2

You want to be using Stream#flatMap instead of Stream#map.

TuGordoBello
  • 4,350
  • 9
  • 52
  • 78
Jacob G.
  • 28,856
  • 5
  • 62
  • 116