CptDayDreamer
CptDayDreamer

Reputation: 1794

DTO List Mapping / Streaming

It's maybe an easy problem but I won't get the best solution. My method like looks this:

public static MlpConfigDto toMlpConfigDto(MlpConfig mlpConfig) {
    return new MlpConfigDto().setActivationFunction(mlpConfig.getActivationFunction().getType().name())
            .setBatchSize(mlpConfig.getBatchSize()).setDescription(mlpConfig.getDescription())
            .setEpochNumber(mlpConfig.getEpochNumber()).setId(mlpConfig.getId())
            .setLastUpdated(mlpConfig.getLastUpdated())
            .setLayers(new List<LayerDto>(
                    mlpConfig.getLayers().stream().map(layer -> new ModelMapper().map(layer, LayerDto.class)))
                            .collect(Collectors.toList()));
}

The last part of course does not work because there is no new List<LayerDto> in Java. With a Set this works like a charm but I need a List here. How to do it the easiest way for Lists then?

For Sets it would look like this:

.setLayers(new HashSet<LayerDto>(
    mlpConfig.getLayers().stream().map(layer -> new ModelMapper().map(layer, LayerDto.class)))
            .collect(Collectors.toSet()));
}

Upvotes: 0

Views: 923

Answers (1)

Andronicus
Andronicus

Reputation: 26066

The following line returns a list:

mlpConfig.getLayers()
    .stream()
    .map(layer -> new ModelMapper().map(layer, LayerDto.class))
    .collect(Collectors.toList())

There is no need to wrap it into another collection.

Upvotes: 1

Related Questions