2016-03-29 166 views
0

我想避免這個嵌套for循環,並用java8中的任何更好的技術取代它。我讀了java8中的流,但在這個特定的代碼中,我怎樣才能使用java8流或其他任何東西來使代碼更好,主要避免嵌套循環?更好的代碼替換嵌套for循環使用Java 8

List<Country> countryList=new ArrayList<Country>(); 
List<CountryDTO> countryDtoList=new ArrayList<CountryDTO>(); 
List<CityDTO> cityDtoList=new ArrayList<CityDTO>(); 
countryList.forEach(country->{ 
    CountryDTO countryDto=new CountryDTO(); 
    countryDto.setCountryId(country.getCountryId()); 
    countryDto.setCountryName(country.getCountryName()); 
    countryDto.setCapital(country.getCapital()); 
    List<City> cityList=new ArrayList<City>(); 
    cityList=cityRepository.getCitiesForCountry(country.getCountryId()); 
    cityList.forEach(city->{ 
    CityDTO cityDto=new CityDTO(); 
    cityDto.setCityId(city.getCityId()); 
    cityDto.setCityName(city.getCityName()); 
    cityDtoList.add(cityDto); 
    }); 
    countryDto.setCities(cityDtoList); 
}); 
+1

不要使用'forEach' ......通過這個https://docs.oracle.com/javase/tutorial/collections/streams/ – Tunaki

+1

去,我會頂替'通過增強'for'循環forEach' 。嵌套的'for'循環沒有任何問題。 –

+1

我會考慮使用構造函數。這將使代碼更清潔,並允許您更輕鬆地使用映射。 –

回答

2

您應該應用一般的重構技術並以適當的方法提取邏輯。通常使用流和一系列地圖調用代替forEach方法更好。

List<Country> countryList = ...; 
List<CountryDTO> countryDtoList = countryList.stream() 
              .map(MyClass::countryToDTO) 
              .collect(toList()); 

private static CountryDTO countryToDTO(Country country) { 
    CountryDTO countryDto=new CountryDTO(); 
    countryDto.setCountryId(country.getCountryId()); 
    countryDto.setCountryName(country.getCountryName()); 
    countryDto.setCapital(country.getCapital()); 
    List<CityDTO> cityDtoList = cityRepository.getCitiesForCountry(country.getCountryId()) 
              .stream() 
              .map(MyClass:cityToDTO) 
              .collect(toList()); 
    countryDto.setCities(cityDtoList); 
    return countryDTO; 
} 

private static CityDTO cityToDTO(City city) { 
    CityDTO cityDto=new CityDTO(); 
    cityDto.setCityId(city.getCityId()); 
    cityDto.setCityName(city.getCityName()); 
    return cityDTO; 
} 
+0

雖然試圖出碼 列表 cityDtoList = cityRepository.getCitiesForCountry(country.getCountryId()) .stream() .MAP(MyClass的:cityToDTO) .collect(toList()); 我在我的IDE上發現錯誤標記,說明類型CityDTO沒有定義適用於此的CityDTO(城市)。我無法猜測爲什麼會出現這樣的錯誤。 –

+1

你是否打電話給'CityDTO :: new'?你有沒有定義這樣的構造函數?如果您使用我發佈的代碼,則需要將「MyClass」替換爲「cityToDTO」靜態方法所在的類。 – assylias

+0

感謝@assylias現在罰款...錯誤不再存在。 –

3

我會轉換構造函數或工廠添加到CountryDTO

List<Country> countryList = ... some data 
List<CountryDTO> dtoList = countryList.stream() 
             .map(CountryDTO::new) 
             .collect(Collectors.toList()); 

您將需要一個構造函數添加到CountryDTO

public CountryDTO(Country country) { 

或者你可以使用一個工廠方法

public static CountryDTO from(Country country) {