Dev*_*dra 5 java java-8 java-stream
我正在写一个方法,它将返回regiondata的列表,我正在以下面的方式做但是得到错误
@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;
}
Run Code Online (Sandbox Code Playgroud)
我收到了错误
type mismatch: cannot convert from List<List<RegionData>> to List<RegionData>
Run Code Online (Sandbox Code Playgroud)
on line regionData = countriesIso.stream().map(c-> i18nFacade.getRegionsForCountryIso(c)).collect(Collectors.toList());
函数i18nFacade.getRegionsForCountryIso(c)返回一个区域数据列表,我想将这些列表组合成单个列表.我尝试使用lambda但无法这样做.
您需要将flatMap与stream一起使用.
regionData = countriesIso.stream().flatMap(c -> i18nFacade.getRegionsForCountryIso(c).stream()).collect(Collectors.toList());
使用flatMap:
返回一个流,该流由通过将提供的映射函数应用于每个元素而生成的映射流的内容替换此流的每个元素的结果组成。
regionData = countriesIso
.stream()
.flatMap(c -> i18nFacade.getRegionsForCountryIso(c)
.stream())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4785 次 |
| 最近记录: |