簡體   English   中英

將Pojo列表轉換為嵌套列表

[英]Convert a Pojo list to nested lists

我有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模型。 有人可以幫助如何實現這一目標。

您正在尋找的是關系數據庫的一對多關聯。 所有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;

}

如果我理解正確你有表中的列表,你希望它映射到你的POJO類。 但問題是如果我理解正確,你在表中有重復的值。 我想你在表1中有這些數據。美國,佛羅里達,邁阿密2.美國,佛羅里達,薩拉索塔

問題將出在表格中。 我認為你應該在單獨的表中拆分每一列,並通過foreing key加入,這樣會更好。 您可以創建select並加入另一個表,結果將添加到列表中。 現在你需要創建循環。


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM