I'm grouping a list of objects in a Map<AvaliadorEventoDTO, Map<TipoQuestionario, List<EventoQuestaoDTO>>>
, then I'm traversing map to create a new object with the information already grouped.
List<EventoQuestaoDTO> list = new ArrayList<EventoQuestaoDTO>(
eventoQuestaoService.buscarEventoQuestaoDTO(empresa, evento, idioma,
inscTipoTrabAval.getAvaliadorEvento().getId(), inscTipoTrabAval.getInscricaoTipoTrabalho().getId(), inscTipoTrabAval.getId()));
avaliacoes = new ArrayList<EventoAvaliacaoDTO>();
Map<AvaliadorEventoDTO, Map<TipoQuestionario, List<EventoQuestaoDTO>>> map = list.stream()
.collect(Collectors.groupingBy(EventoQuestaoDTO::getAvaliadorEvento, Collectors.groupingBy(EventoQuestaoDTO::getTipoQuestionario)));
for (Map.Entry<AvaliadorEventoDTO, Map<TipoQuestionario, List<EventoQuestaoDTO>>> avaliador : map.entrySet()) {
List<QuestionarioDTO> questionarios = new ArrayList<QuestionarioDTO>();
for(Map.Entry<TipoQuestionario, List<EventoQuestaoDTO>> questionario : avaliador.getValue().entrySet()) {
questionarios.add(new QuestionarioDTO(questionario.getKey(), questionario.getValue()));
}
avaliacoes.add(new EventoAvaliacaoDTO(avaliador.getKey(), questionarios));
}
But I would like to optimize the for in lambdas expressions, to transform the Map into a DTO QuestionarioDTO list, without needing to use the for and thus use fewer lines.
Could someone give a light?
CodePudding user response:
The following should work:
List<EventoAvaliacaoDTO> avaliacoes = map.entrySet().stream().map(entry -> {
List<QuestionarioDTO> questionarios = entry.getValue().entrySet().stream().map(innerEntry ->
new QuestionarioDTO(innerEntry.getKey(), innerEntry.getValue())
).collect(Collectors.toList());
return new EventoAvaliacaoDTO(avaliador.getKey(), questionarios);
}).collect(Collectors.toList());
Is it more readable than nested for loops? I really doubt it. Keep in mind that not everything should be done using Java streams.
CodePudding user response:
Here is a simple example:
Map<String, String> map = new HashMap<String, String>();
map.put("key 1", "value 1");
map.put("key 2", "value 2");
map.put("key 3", "value 3");
List<Object> list = new ArrayList<Object>();
map.forEach((key, value) -> list.add(key " : " value));