gpt4 book ai didi

java - 将 Pojo 列表转换为嵌套列表

转载 作者:行者123 更新时间:2023-11-29 04:16:05 27 4
gpt4 key购买 nike

我有 3 个实体:国家、州、城市我将他们的 POJO 写成:

class Country{
String countryName;
List<State> states;
}

class State{
String stateName;
List<City> cities;
}

class City{
String cityName;
}

我的数据库表如下:

Goegraphy
---------
countryName | stateName | cityName

现在,为了从数据库中获取数据,我制作了另一个 POJO:

class Geography{
String countryName;
String stateName;
String cityName;
}

我有一个地理对象列表。但我的要求是现在将此列表转换为早期的 Country-State-City 模型。有人可以帮助实现这一目标。

最佳答案

您正在寻找的是 One to Many关系数据库的关联。所有 JPA 实现都可以很好地为您完成,而无需实现 Geography Pojo。

但如果您坚持手动执行此操作,这里有一种使用 Java 8 流进行操作的优化方法

class Country {

public Country(String countryName) {
this.countryName = countryName;
this.states = new ArrayList<>();
}

String countryName;
List<State> states;

}

class State {

public State(String stateName) {
this.stateName = stateName;
this.cities = new ArrayList<>();
}


String stateName;
List<City> cities;
}

class City {
public City(String cityName) {
this.cityName = cityName;
}

String cityName;
}

class Geography {
String countryName;
String stateName;
String cityName;
}


List<Country> buildFromGeographies(List<Geography> geos) {

List<Country> result = new ArrayList<>();

for (Geography geo : geos) {
Optional<Country> country1 = result.stream().filter(country -> country.countryName.equals(geo.countryName)).findFirst();
Country country = country1.orElseGet(() -> {
Country newOne = new Country(geo.countryName);
result.add(newOne);
return newOne;
});

Optional<State> state1 = country.states.stream().filter(state -> state.stateName.equals(geo.stateName)).findFirst();
State state = state1.orElseGet(() -> {
State newOne = new State(geo.stateName);
country.states.add(newOne);
return newOne;
});

// taking for granted there is no duplicates in your data set
state.cities.add(new City(geo.cityName));
}

return result;

}

关于java - 将 Pojo 列表转换为嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343351/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com