Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collect list from lambda expression [duplicate]

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.

like image 869
Devendra Avatar asked Dec 14 '16 05:12

Devendra


2 Answers

You need to use flatMap with stream. regionData = countriesIso.stream().flatMap(c -> i18nFacade.getRegionsForCountryIso(c).stream()).collect(Collectors.toList());

like image 175
Raghav Avatar answered Sep 19 '22 10:09

Raghav


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());
like image 42
thegauravmahawar Avatar answered Sep 22 '22 10:09

thegauravmahawar