我想避免這個嵌套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);
});
不要使用'forEach' ......通過這個https://docs.oracle.com/javase/tutorial/collections/streams/ – Tunaki
去,我會頂替'通過增強'for'循環forEach' 。嵌套的'for'循環沒有任何問題。 –
我會考慮使用構造函數。這將使代碼更清潔,並允許您更輕鬆地使用映射。 –