不能使用Java stream()映射级联列表的字段



我有一个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());

最新更新