无法使用 Java stream() 映射级联列表的字段
Cannot map field of cascade list using Java stream()
我有一个 List<Country>
,它有 List<City>
。我想使用 Java stream() 检索国家/地区列表中所有城市的 UUID
列表,但我无法正确映射它们。通常我可以获得列表的 UUID
字段,但是有级联列表,我找不到合适的解决方案。那么,我该如何解决这个问题呢?我应该使用 flatMap
吗?
List<UUID> cityUUIDList = countryList.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());
您还可以像这样获取 UUID
的列表:
List<UUID> cityUUIDList = countryList.stream()
.map(Country::getCities)
.flatMap(List::stream)
.map(CityDTO:::getUuid)
.collect(Collectors.toList());
我有一个 List<Country>
,它有 List<City>
。我想使用 Java stream() 检索国家/地区列表中所有城市的 UUID
列表,但我无法正确映射它们。通常我可以获得列表的 UUID
字段,但是有级联列表,我找不到合适的解决方案。那么,我该如何解决这个问题呢?我应该使用 flatMap
吗?
List<UUID> cityUUIDList = countryList.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());
您还可以像这样获取 UUID
的列表:
List<UUID> cityUUIDList = countryList.stream()
.map(Country::getCities)
.flatMap(List::stream)
.map(CityDTO:::getUuid)
.collect(Collectors.toList());