I am want to avoid this nested for loop and replace it with any better technique in java8. I read about streams in java8 but in this particular code how can I use java8 streams or anything else to make the code better and mainly avoid the nested loop?
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... Go through this docs.oracle.com/javase/tutorial/collections/streamsforEachby enhancedforloops. There's nothing wrong with nestedforloops.