使用Java 8在嵌套for循环中更好地替换代码

时间:2016-03-29 09:48:01

标签: java java-8 java-stream

我想避免这个嵌套的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);
});

2 个答案:

答案 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;
}