我有一个List<Country>
,它有List<City>
。我想使用Java流()检索国家列表中所有城市的UUID
列表,但我无法正确地映射它们。通常我可以得到列表的UUID
字段,但是有级联列表,我找不到合适的解决方案。那么,我该如何解决这个问题呢?我应该使用flatMap
吗?
List<UUID> cityUUIDList = countryList.stream().map(CityDTO::getUuid)
.collect(Collectors.toList());
您也可以像这样获得UUID
的列表:
List<UUID> cityUUIDList = countryList.stream()
.map(Country::getCities)
.flatMap(List::stream)
.map(CityDTO:::getUuid)
.collect(Collectors.toList());
您需要使用flatMap()
方法,假设您有如下内容:
class Country {
List<CityDTO> cities = new ArrayList<>();
}
class CityDTO {
UUID uuid;
UUID getUuid() {
return uuid;
}
}
List<UUID> cityUUIDList = countryList.stream()
.flatMap(c -> c.cities.stream())
.map(CityDTO::getUuid)
.collect(Collectors.toList());