이 중첩 된 for 루프를 피하고 java8의 더 나은 기술로 바꾸고 싶습니다. java8의 스트림에 대해 읽었지만이 특정 코드에서 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);
});
일반적인 리팩토링 기술을 적용하고 적절한 방법으로 논리를 추출해야합니다. 그리고 일반적으로 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;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다