javaspring-boothibernatejava-streammodelmapper

Java Stream: How to map multiple value to a single DTO?


I have a List result in my Spring Boot service method as shown below:

Country:
String name;
List<State> states;
State:
String name;
Long population;
List<Town> towns;
Town:
String name;

I return Country list from my repository and it has all the related State and Town date for each Country. I want to map this data to a DTO as shown below:

public class CountryDTO {

    private Long id;

    private String name;

    private Long population; //population sum of states by country

    private List<Town> towns;

    //constructor
}

So, how can I map my Country entity to this CountryDTO properly as explained above? I need the following data:

Country name Sum of population by each country Towns of each country

Update: Here is my service method where I tried to use Java Stream and then also ModelMapper, but cannot return desired values :(

List<CountryDTO> countries = countryRepository.findAll().stream()
                .flatMap(x -> x.getStates().stream())
                .map(x -> new CountryDTO(x.getCountry(), <-- need to return sum of population here -->, ObjectMapperUtils.mapAll(x.getTowns(), TownDTO.class)))
                .toList();

Solution

  • List<CountryDTO> res = countries.stream().map(c -> new CountryDTO(c.getName(), 
          c.getStates().stream().mapToInt(State::getPopulation).sum(), 
          c.getStates().stream().flatMap(s -> s.getTowns().stream()).toList())).toList();