2016-12-14 45 views
2

我寫這將返回regiondata列表的方法列表,我在做下面的方式,但得到的錯誤如何收集lambda表達式

@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; 
    } 

我收到錯誤的

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

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

函數i18nFacade.getRegionsForCountryIso(c)返回區域數據列表,我想將這些列表組合成單個列表。 我試着用lambda但無法這樣做。

+2

[上造型的註記。](https://www.youtube.com/watch?v=1OpAgZvYXLQ&t=4632) – shmosel

回答

2

您需要在流中使用flatMap。 regionData = countriesIso.stream().flatMap(c -> i18nFacade.getRegionsForCountryIso(c).stream()).collect(Collectors.toList());

2

使用flatMap

返回由與由 產生應用提供映射函數的每個元素映射流的內容替換該流中的每個元素 的結果的流。

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