我想避免这个嵌套的for循环,并用java8中的任何更好的技术替换它。我在java8中读到了关于java的流,但是在这个特定的代码中,我如何使用java8流或其他任何东西来改善代码并主要避免嵌套循环?
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);
});
答案 0 :(得分: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) {
答案 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;
}